Testing React-Query with Mock Service Worker

In this article i’ll show you how to test React-Query with Mock Service Worker(MSW).

Prerequisites

This article will be dependent on a previous articles we published about how to test React-Query Infinite Queries With Jest And React-testing-library. It’s preferred to read those articles before continuing in this one.

  1. How to test Infinite Query With Jest And React-testing-library – Part 1.
  2. How to test Infinite Query With Jest And React-testing-library – Part 2.

Note: Full source code that have example for testing hooks using both libraries (Nock and MSW):

Let’s get started!

Initial Setup:

1- Let’s install MSW as dev-dependency.

npm install msw --save-dev
# or
yarn add msw --dev

2- Create new file.
Let’s create a new file under the __tests__ folder and give it any name, it will be useInfiniteQueryUsingMSW.test.tsx in this article.

3- Inside the newly created file, let’s create a new QueryCache / QueryClient.

QueryCache is needed to invalidate/remove the cache after each test running completed. And QueryClient is needed to make sure our tests are isolated from others.

Also we’ve reused the wrapper component from the previous articles, It’s used to make sure we’re running tests inside QueryClientProvider scope as a component.

import { renderHook } from '@testing-library/react-hooks';
import { ReactNode } from 'react';
import { QueryCache } from 'react-query';
import { rest } from "msw";
import { setupServer } from 'msw/node';
import { QueryClient, QueryClientProvider } from 'react-query';
import { useUsersQuery } from '../useInfiniteQuery';
import { responseForPage0, responseForPage1, responseForPage2 } from '../fixtures';

const queryCache = new QueryCache();
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: false,
        },
    },
});

const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={queryClient}>
        {children}
    </QueryClientProvider>
);

4- Add a mock server handler using MSW setupServer

const server = setupServer(
    rest.get("https://dummyapi.io/data/v1/user", (req, res, ctx) => {
        const pageNumber = req.url.searchParams.get('page');
        let response;

        if (pageNumber === '0') {
            response = responseForPage0;
        } else if (pageNumber === '1') {
            response = responseForPage1;
        } else if (pageNumber === '2') {
            response = responseForPage2;
        }

        return res(
            ctx.json(response)
        );
    }),
);

We’ve created a new rest.get handler with an endpoint defined by the path https://dummyapi.io/data/v1/user

Then we’ve extracted the page query parameter from req.url.searchParams so that we can return the mocked response based on the page value.

As shown at line 6, we’re checking the page parameter value is 0 then we return the mocked responseForPage0and so on for pages 1 and 2.

At line 14, we return the mocked response as json value.

5- Add Jest hooks

beforeAll(() => server.listen());
afterEach(() => {
    server.resetHandlers();
    queryCache.clear()
});
afterAll(() => server.close());

beforeAll: We call the server.listen() function that is created in the previous step to start intercepting any request matching the URL path.

afterEach: In this hooks, we’re triggering server.resetHandlers() to reset the handlers after each test suite running completed. As well we’re clearing the query cache.

afterAll: Close the server after all tests running is completed.

6- Add the test suite implementation.

describe('useUsersQuery', () => {
    it('fetches the users list', async () => {
        // Fetches Page 0
        const { result, waitFor } = renderHook(() => useUsersQuery(), { wrapper });
        await waitFor(() => result.current.isSuccess);
        expect(result.current.data?.pages[0]).toStrictEqual({ results: responseForPage0.data, next: 1 });

        // Fetches Page 1
        result.current.fetchNextPage();
        await waitFor(() => result.current.isFetching);
        await waitFor(() => !result.current.isFetching);

        expect(result.current.data?.pages).toStrictEqual([
            { results: responseForPage0.data, next: 1 },
            { results: responseForPage1.data, next: 2 },
        ]);

        // Fetches Page 2
        result.current.fetchNextPage();
        await waitFor(() => result.current.isFetching);
        await waitFor(() => !result.current.isFetching);

        expect(result.current.data?.pages).toStrictEqual([
            { results: responseForPage0.data, next: 1 },
            { results: responseForPage1.data, next: 2 },
            { results: responseForPage2.data, next: undefined },
        ]);
    });
});

Putting it all together:

import { renderHook } from '@testing-library/react-hooks';
import { ReactNode } from 'react';
import { rest } from "msw";
import { setupServer } from 'msw/node';
import { QueryCache } from 'react-query';
import { QueryClient, QueryClientProvider } from 'react-query';
import { responseForPage0, responseForPage1, responseForPage2 } from '../fixtures';
import { useUsersQuery } from '../useInfiniteQuery';

const queryCache = new QueryCache();
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: false,
        },
    },
})

const wrapper = ({ children }: { children: ReactNode }) => (
    <QueryClientProvider client={queryClient}>
        {children}
    </QueryClientProvider>
);

const server = setupServer(
    rest.get("https://dummyapi.io/data/v1/user", (req, res, ctx) => {
        const pageNumber = req.url.searchParams.get('page');
        let response;

        if (pageNumber === '0') {
            response = responseForPage0;
        } else if (pageNumber === '1') {
            response = responseForPage1;
        } else if (pageNumber === '2') {
            response = responseForPage2;
        }

        return res(
            ctx.json(response)
        );
    }),
);

beforeAll(() => server.listen());
afterEach(() => {
    server.resetHandlers();
    queryCache.clear()
});
afterAll(() => server.close());

describe('useUsersQuery', () => {
    it('fetches the users list', async () => {
        // Fetches Page 0
        const { result, waitFor } = renderHook(() => useUsersQuery(), { wrapper });
        await waitFor(() => result.current.isSuccess);
        expect(result.current.data?.pages[0]).toStrictEqual({ results: responseForPage0.data, next: 1 });

        // Fetches Page 1
        result.current.fetchNextPage();
        await waitFor(() => result.current.isFetching);
        await waitFor(() => !result.current.isFetching);

        expect(result.current.data?.pages).toStrictEqual([
            { results: responseForPage0.data, next: 1 },
            { results: responseForPage1.data, next: 2 },
        ]);

        // Fetches Page 2
        result.current.fetchNextPage();
        await waitFor(() => result.current.isFetching);
        await waitFor(() => !result.current.isFetching);

        expect(result.current.data?.pages).toStrictEqual([
            { results: responseForPage0.data, next: 1 },
            { results: responseForPage1.data, next: 2 },
            { results: responseForPage2.data, next: undefined },
        ]);
    });
});

Run the tests in the terminal and you should get 100% coverage over the new implementation of MSW

Testing React-Query with Mock Service Worker
Testing React-Query with Mock Service Worker

Redundant usage of query parameters.


Note: If you try to setup multiple handlers for the same url with different query parameters, MSW will complain about that and you will get a kind of the following error:

[MSW] Found a redundant usage of query parameters in the request handler URL for “GET https://dummyapi.io/data/v1/user?page=0&limit=50”. Please match against a path instead and access query parameters in the response resolver function using “req.url.searchParams”.

const server = setupServer(
    rest.get("https://dummyapi.io/data/v1/user?page=0&limit=50", (req, res, ctx) => {
        return res(
            ctx.json(responseForPage0)
        );
    }),
    rest.get("https://dummyapi.io/data/v1/user?page=0&limit=50", (req, res, ctx) => {
        return res(
            ctx.json(responseForPage1)
        );
    }),
);

// Will results in the following warning: 👇
    [MSW] Found a redundant usage of query parameters in the request handler URL for "GET https://dummyapi.io/data/v1/user?page=0&limit=50". Please match against a path instead and access query parameters in the response resolver function using "req.url.searchParams".


So for this reason, we’ve declared single handler at step 4, and parsed the request query parameters to return the response based on the page value.

That’s It!

Full source code: use-infinite-query.

Part1: How to test Infinite Query With Jest And React-testing-library

Part2: How to test Infinite Query With Jest And React-testing-library

And as always, happy coding! 🥳👋🏻

Photo from unsplash.

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: