Search code examples
firebasereact-nativejestjsreact-test-renderer

How to test Alert in React Native with Jest


So in my program, when a user logs in, if all credentials are correct they will proceed to the next page if any details are missing or incorrect format, and alert is shown on screen.

How do I test using Jest in React Native if the alert has been displayed after a button press, and confirm that the text of the alert is correct?

Some of my component is shown below:

...
.catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    alert(errorMessage)
  });

The error text is generated by Google's Firebase, but I do know what it is.


Solution

  • Assuming you are using react-native's Alert and calling it yourself, you can spy on it like so:

    import { Alert } from 'react-native';
    
    jest.spyOn(Alert, 'alert');
    

    You can then check that it has been called, and what arguments were used:

    expect(Alert.alert).toHaveBeenCalledWith(errorMessageText)
    

    [Update] it is also possible to test interactions with the alert:

    const mockOnPress = jest.fn()
    
    Alert.alert('Title', 'Message', [{text: 'OK', onPress: mockOnPress}])
    
    /** 
     * here we inspect the mock to get:
     * - the latest call to Alert.alert (`calls[0]`)
     * - its third argument (`calls[0][2]`), which is the buttons config array
     * - the first button in the array and its onPress (`calls[0][2][0].onPress()`)
     */
    Alert.alert.mock.calls[0][2][0].onPress()
    
    expect(mockOnPress).toBeCalled()