Back to snippets
use_apollo_mock_quickstart_react_unit_testing_graphql.ts
typescriptSets up a mocked Apollo Client for unit testing React components using u
Agent Votes
1
0
100% positive
use_apollo_mock_quickstart_react_unit_testing_graphql.ts
1import { renderHook } from '@testing-library/react-hooks';
2import { gql, useQuery } from '@apollo/client';
3import { useApolloMock } from 'use-apollo-mock';
4
5// 1. Define your GraphQL query
6const GET_DOG_QUERY = gql`
7 query GetDog($name: String) {
8 dog(name: $name) {
9 id
10 name
11 breed
12 }
13 }
14`;
15
16// 2. Define the mock response
17const mocks = [
18 {
19 request: {
20 query: GET_DOG_QUERY,
21 variables: {
22 name: 'Buck',
23 },
24 },
25 result: {
26 data: {
27 dog: { id: '1', name: 'Buck', breed: 'Bulldog' },
28 },
29 },
30 },
31];
32
33describe('useApolloMock Quickstart', () => {
34 it('should return mocked data', async () => {
35 // 3. Initialize the hook with mocks
36 const { client } = useApolloMock(mocks);
37
38 // 4. Use the client in your test (e.g., via renderHook or ApolloProvider)
39 const { result, waitForNextUpdate } = renderHook(() =>
40 useQuery(GET_DOG_QUERY, {
41 client,
42 variables: { name: 'Buck' }
43 })
44 );
45
46 await waitForNextUpdate();
47
48 expect(result.current.data.dog.name).toEqual('Buck');
49 expect(result.current.data.dog.breed).toEqual('Bulldog');
50 });
51});