Learn Relay/
← 0911 →

10 - test usePreloadedQuery

Learn how to test components using usePreloadedQuery with @testing-library.

PostDetail reads a query preloaded by the route loader (see routes.tsx). This exercise runs in test mode: instead of rendering the app, every *.spec.tsx file is executed (jest/vitest-like API) and the results show up in the Tests tab.

Exercise

  • Add the test inside components/feed/post/__tests__/PostDetail.spec.tsx
  • render the PostDetail route using @testing-library
  • use the withProviders helper (test/withProviders.tsx) to add all Providers the component needs
  • mock the PostDetailQuery before loadQuery is called by the route loader
  • assert the post content is rendered

Extras

  • add another test (it), testing a post that was not found

Code Helpers

  • withProviders adds all Providers (Relay, router, Suspense, ErrorBoundary), to make tests as close to real usage as possible
const Root = withProviders({
  routes,
  initialEntries,
  environment,
});
  • queue a pending operation, usually a query that will be used by loadQuery
environment.mock.queuePendingOperation(query, variables);
  • mock a queued pending operation using custom mock resolvers
environment.mock.queueOperationResolver(operation =>
  MockPayloadGenerator.generate(operation, customMockResolvers),
);
  • mock GraphQL data
const customMockResolvers = {
  User: () => ({
    name: 'Relay',
  }),
};
Next: test useFragment →
Loading editor…
test runner
components rendered by tests show up here
Running tests…