你会如何在Alert中模拟'onPress'? [英] How would you mock 'onPress' within Alert?

查看:109
本文介绍了你会如何在Alert中模拟'onPress'?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够模拟警报以测试它的警报方法正在被调用,但我真正想要测试的是按警报中的确定按钮。

I'm able to mock out the Alert to test that it's alert method is being called, but what I really want to test is pressing the ok button within the alert.

import { Alert } from 'react-native';

it('Mocking Alert', () => {
    jest.mock('Alert', () => {
        return {
          alert: jest.fn()
          }
        };
      });

    const spy = jest.spyOn(Alert, 'alert');
    const wrapper = shallow(<Search />);

    wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
    expect(spy).toHaveBeenCalled(); //passes
})

我绝对不确定如何测试。这是我试图测试的通用组件。

I'm absolutely unsure of how to test for that though. Here is a generic component with what I am trying to test.

export default class Search extends Component{

    state = {
      someState: false
    }

    confirmSubmit(){
      this.setState(state => ({someState: !state.someState}))
    }

    onPress = () => {
      Alert.alert(
        'Confirm',
        'Are you sure?'
        [{text: 'Ok', onPress: this.confirmSubmit}] //<-- want to test this
      )
    }

    render(){
      return(
       <View>
         <Button title='Submit' onPress={this.onPress}
       </View>
      )
    }
}

有没有人试过这个?

推荐答案

我会模拟模块并将其导入以测试间谍。然后触发click事件。这会打电话给间谍。从间谍中你可以使用获取它所使用的参数。 mock.calls 获取 onPress 方法并调用它。然后你可以测试组件的状态。

I would mock the module and import it to test on the spy. Then trigger the click event. This will call spy. From the spy you can get the params it was called with using mock.calls to get the onPress method and call it. Then you can test the state of your component.

import Alert from 'Alert'

jest.mock('Alert', () => {
    return {
      alert: jest.fn()
    }
});


it('Mocking Alert', () => {
    const wrapper = shallow(<Search />);
    wrapper.findWhere(n => n.props().title == 'Submit').simulate('Press');
    expect(Alert.alert).toHaveBeenCalled(); // passes
    Alert.alert.mock.calls[0][2][0].onPress() // trigger the function within the array
    expect(wrapper.state('someState')).toBe(true)
})

这篇关于你会如何在Alert中模拟'onPress'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆