How to test Alert in React Native with Jest

Viewed 7442

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.

2 Answers

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

in your spec file.

add

export class FakeSubject {
    next(value: any) {}
    asObservable() {}
}

configure your testbed:

TestBed.configureTestingModule({
    providers: [{ provide: Subject, useClass: FakeSubject }],
}),

add a service getter before each test.

beforeEach(() => {
    service = TestBed.get(AlertService);
});

add test, you can use this example for another test.

it('success alert ', () => {
    const spy = spyOn(service, 'alert');
    const message = 'hi!';
    service.success(message);
    expect(spy).toHaveBeenCalledWith(new Alert(message, AlertType.Success));
});

and your utility methods:

it('alert ', () => {
    subject = service['subject'];
    const spy = spyOn(subject, 'next');
    const alert = new Alert('hi', AlertType.Success);
    service.alert(alert);
    expect(spy).toHaveBeenCalledWith(alert);
});

it('clear ', () => {
    subject = service['subject'];
    const spy = spyOn(subject, 'next');

service.clear();
expect(spy).toHaveBeenCalledWith(null);
});
Related