Learn Relay/
← 1113 →

12 - test useMutation

Learn how to test components that use useMutation.

The spec already has the tests from the previous exercise. Complete the click in the like button test.

Exercise

  • render the PostLikeButton component using @testing-library (same as 11-testUseFragment)
  • click on the like button (data-testid='likeButton')
  • assert the mutation is called with the right variables
  • mock the mutation response and assert the new likesCount in the DOM

Extras

  • assert the optimistic response (likesCount + 1) is rendered before resolving the mutation
  • test clicking the button of a post you already liked (PostUnLikeMutation)

Code Helpers

  • click a button
fireEvent.click(likeButton);
  • wait the mutation to be called
await waitFor(() => environment.mock.getMostRecentOperation());
  • get the mutation operation
const mutationOperation = environment.mock.getMostRecentOperation();
mutationOperation.fragment.variables; // { input: { post: 'postId' } }
  • resolve the mutation
environment.mock.resolveMostRecentOperation(operation =>
  MockPayloadGenerator.generate(operation, customMockResolvers),
);

tricks for the mutation response

Don't resolve the mutation inside an asynchronous act: the mutation response must be synchronous (act(() => { ... })).

Next: Declarative directives →
Loading editor…
test runner
components rendered by tests show up here
Running tests…