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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: