How would you mock 'onPress' within Alert?

2019-04-23 05:28发布

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>
      )
    }
}

Has anyone ever attempted this?

1条回答
该账号已被封号
2楼-- · 2019-04-23 06:07

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)
})
查看更多
登录 后发表回答