How would you mock 'onPress' within Alert?
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)
})
I had the same problem with testing Alert and trying to simulate onPress for the Alert. I'm implementing my code with TypeScript. I managed to handle this by using spyOn like:
const spyAlert = jest.spyOn(Alert, 'alert');
and then to use onPress you need to ignore type checking for the line otherwise you'll get - Cannot invoke an object which is possibly 'undefined'.
// @ts-ignore
spyAlert.mock.calls[0][2][0].onPress();