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?
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 theonPress
method and call it. Then you can test the state of your component.