test if a toast message was shown with Jest

25 Views Asked by At

I'm testing my react native application with Jest and I want to test when toast shows a message.

I'm using toast like this in one of my callbacks :

if (pinMismatch) {
       Toast.show({
              type: "error",
              text1: "invalid answer",
       });
}

And I want to check in my test below that the message is shown :

    it('handles unsuccessful registration due to PIN mismatch', async () => {
        const { getByText, getByTestId } = render(
                    <NavigationContainer>
                               <Registration navigation={mockNavigation} />
                    </NavigationContainer>
              );

        fireEvent.changeText(getByTestId('pin'), '123456');
        fireEvent.changeText(getByTestId('confirm-pin'), '654321');
        const registrationButton = getByText("register");
        fireEvent.press(registrationButton);

        await waitFor(() => {
                 // I want to check here that "invalid answer" was shown
        }

How can I do that ?

1

There are 1 best solutions below

0
Spencer Wood On

You can use the getByText matcher, or the async findByText matcher if the toast is shown asynchronously and you need to wait for it to appear.

test('...', async () => {
  //...
  expect(await screen.findByText('invalid answer')).toBeInTheDocument();
});