1

For this test case, I am testing a form to see if an error message appears in the DOM after the form is submitted and the response from the server returns with an error. I am using 'MSW' (Mocked Service Worker JS) to mock out the API requests and responses for the form. In the terminal whenever I run the test with jest it fails, but after I setup a screen.debug() within the test I wrote to check whether the error message was present or not I discovered that the error message was actually present.

The test case fails with this message:

 FAIL  src/components/Form/Form.test.tsx
  Form
    ○ skipped Should show "Add User" button
    ○ skipped Should open modal, when button is pressed
  Form submit
    ✕ Should show an error alert message when form fails to submit (519 ms)
    ○ skipped Should show a "success" alert message when form is successfully submitted
  Form validation
    ○ skipped Form validation successfully handles invalid user input
    ○ skipped Form validation succesfully handles valid user input

  ● Form submit › Should show an error alert message when form fails to submit

    Failed to submit form!

      at new ApolloError (node_modules/@apollo/client/errors/index.js:29:28)
      at node_modules/@apollo/client/core/QueryManager.js:91:47
      at both (node_modules/@apollo/client/utilities/observables/asyncMap.js:16:53)
      at node_modules/@apollo/client/utilities/observables/asyncMap.js:9:72
      at Object.then (node_modules/@apollo/client/utilities/observables/asyncMap.js:9:24)
      at Object.next (node_modules/@apollo/client/utilities/observables/asyncMap.js:17:49)
      at notifySubscription (node_modules/zen-observable/lib/Observable.js:135:18)
      at onNotify (node_modules/zen-observable/lib/Observable.js:179:3)
      at SubscriptionObserver.next (node_modules/zen-observable/lib/Observable.js:235:7)
      at node_modules/@apollo/client/utilities/observables/iteration.js:4:68
          at Array.forEach (<anonymous>)
      at iterateObserversSafely (node_modules/@apollo/client/utilities/observables/iteration.js:4:25)
      at Object.next (node_modules/@apollo/client/utilities/observables/Concast.js:25:21)
      at notifySubscription (node_modules/zen-observable/lib/Observable.js:135:18)
      at onNotify (node_modules/zen-observable/lib/Observable.js:179:3)
      at SubscriptionObserver.next (node_modules/zen-observable/lib/Observable.js:235:7)
      at node_modules/@apollo/client/link/http/createHttpLink.js:103:26

Test Suites: 1 failed, 1 total
Tests:       1 failed, 5 skipped, 6 total
Snapshots:   0 total
Time:        4.032 s, estimated 5 s

Here is the test:

  it.only('Should show an error alert message when form fails to submit', async () => {
    mockServer.use(createUserInviteHandlerException);

    const errorMessage = 'Failed to submit form!';

    userEvent.click(addUserButton);

    const emailTextField = await screen.findByRole('textbox', {name: 'Email'});
    const fullNameTextField = await screen.findByRole('textbox', {name: 'Full Name'});
    const phoneNumberTextField = await screen.findByRole('textbox', {name: 'Phone Number'});
    userEvent.type(emailTextField, 'tess.dinh@onetutree.co');
    userEvent.type(fullNameTextField, 'Nadanuda Bugg');
    userEvent.type(phoneNumberTextField, '9091221233');

    const submitButton = screen.getByText('Send Invitation');
    userEvent.click(submitButton);

    await waitFor(async () =>
      expect(await screen.findByText(errorMessage)).toBeInTheDocument()
    );
  });
});

This is the request handler for the mock server:

export const createUserInviteHandlerException =
  graphql.mutation('CreateUserInvite', (_, res, ctx) => {
    return res(
      ctx.delay(),
      ctx.errors([
        {
          status: 400,
          message: 'Failed to submit form!'
        }
      ])
    );
  });

ninjarogue
  • 19
  • 2
  • 4

2 Answers2

0

Assuming that your test is failing because of the very last bit of the code i.e.

await waitFor(async () =>
  expect(await screen.findByText(errorMessage)).toBeInTheDocument()
);

You can simply update it to this & it should work:

expect(await screen.findByText(errorMessage)).toBeInTheDocument();
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

Okay so it turns out that the problem was that the error response from the mock server was not handled properly. All I had to do was add an onError method to the useMutation hook like so:

const [fnMutate, tuple] = useMutation(CREATE_USER_INVITE_MUTATION, {
  onError: error => console.error(error)
});

ninjarogue
  • 19
  • 2
  • 4