Learn Relay/
← 1012 →

11 - test useFragment

Learn how to test components using useFragment and @relay_test_operation with @testing-library.

PostLikeButton only has a fragment (PostLikeButton_post), so it can't be rendered by itself: we need a test query that spreads its fragment.

Exercise

  • render the PostLikeButton component using @testing-library
  • use the withProviders helper to add all Providers for the component you want to test
  • create a wrapper component that uses usePreloadedQuery with a test query using the @relay_test_operation directive
  • mock the test query with queuePendingOperation + queueOperationResolver
  • call loadQuery before rendering the component
  • assert the post likes count

Extras

  • add another test (it), testing that when likesCount is zero there isn't any number in the DOM

Code Helpers

  • test operation
query PostLikeButtonSpecQuery($id: ID!) @relay_test_operation {
  post: node(id: $id) {
    ...PostLikeButton_post
  }
}
  • import the compiled artifact of the test query
import PostLikeButtonSpecQuery from './__generated__/PostLikeButtonSpecQuery.graphql';
Next: test useMutation →
Loading editor…
test runner
components rendered by tests show up here
Running tests…