Testing Infinite Query With Jest And React-testing-library

In our first article How to test Infinite Query With Jest And React-testing-library, We talked about how to implement React-Query useInfinitieQuery and react-infinite-scroll together to lazy load list of data from the server, and we covered the component testing part of it. However there’s still one part for testing which is testing the custom hook separately from the React component, in this article we will cover the why and how to test the react-query custom hook.

Note: Full source code can be found on the following link:

Why?

In the first part we’ve implemented the browser fetch API in order to fetch the data from the server, which is powerful and good enough to do it’s job, however in our use case, we’ve a lazy loading/pagination feature, which we can’t test using the browser fetch API, There are a lot of reasons for that:

  • Browser Fetch api sends an OPTIONS request.
  • It sends HTTP outbound requests using XHR under the hood.
  • We can’t persist the data for consecutive requests (in our case we need to persist the pagination data so that we can make sure the pagination works as expected).

So for the above reasons, we will be changing the browser fetch api with Axios HTTP client.

Let’s get started!

Initial Setup

We will add two libraries in this article, the first one is Axios for making HTTP requests, and the second one will be nock which is an HTTP server mocking and expectations library.

Let’s install them:

1- Install Axios as dependency:

yarn add axios

2- Install nock as devDependency:

yarn add nock --dev

Now, Let’s create a new file axiosClient.ts file and create axios client instance with the base url set to our dummyApi.io server as the following:

import axios from "axios";

const axiosClient = axios.create({
  baseURL: "https://dummyapi.io",
  headers: {
    "content-type": "application/json",
  },
});

export default axiosClient;

Next, we need to update the implementation of the getData function inside the file useInfiniteQuery.ts

import { useInfiniteQuery } from "react-query";
// 1- Import axiosClient
import axiosClient from "./axiosClient";
import { UsersPage } from "./types";

export async function getData({ pageParam = 0 }) {
  // 2- Update the http client to use axiosClient instead of fetch api
  const response = await axiosClient({
    url: `/data/v1/user?page=${pageParam}&limit=50`,
    method: "GET",
    headers: {
      "app-id": "62f43477f19452557ba1ce76",
    },
  });

  // 3- Destruct the following properties from response.data
  const { data, limit, page, total } = response.data;

  // 4- Update the variables usage
  const pageResponse: UsersPage = {
    results: data,
    next: total > page * limit ? pageParam + 1 : undefined,
  };
  return pageResponse;
}

export const useUsersQuery = () => {
  const query = useInfiniteQuery<UsersPage, Error>("users", getData, {
    getNextPageParam: (lastPage) => lastPage.next,
  });

  return query;
};

The updates includes the following steps:

  1. Import axiosClient.
  2. Update the http client to use axiosClient instead of fetch api.
  3. Destruct the following properties from response.data.
  4. Update the variables usage.

That’s it for updating our implementation to use Axios HTTP client rather than the browser fetch api, try running the app by executing yarn start or npm run start, it should work as expected and as it was before.

Unit Testing

Let’s jump to the testing part, we need to test the custom hook functionality alone.

In order achieve that, First, we need to configure axios adapter to use the node adapter so that nock can intercept axios requests, otherwise axios will be using XHR module to send the requests which will results in the same issue as in the browser fetch api.

1- Go to the src/setupTests.ts file and add the following two line:

import "@testing-library/jest-dom";

// Tell axios to use node adapter while running in testing mode
import axios from 'axios';
axios.defaults.adapter = require('axios/lib/adapters/http');

2- Let’s create a new file under the __tests__ folder with any name, like useInfiniteQuery.test.tsx

and let’s test the pagination/lazy loading step by step, first add the following code to the file

import { renderHook } from '@testing-library/react-hooks';
import nock from 'nock';
import { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { responseForPage0 } from '../fixtures';
import { useUsersQuery } from '../useInfiniteQuery';

// 1- Create a new QueryClient instance with retry = false
const queryClient = new QueryClient({
    defaultOptions: {
        queries: {
            retry: false,
        },
    },
})

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

// 3- Create a test suite
describe('useUsersQuery', () => {
    it('fetches the users list', async () => {

// 4- Create nock request interceptor and return mocked data
        nock('https://dummyapi.io', {
            reqheaders: {
// 5- Mocking the 'app-id' header to return true
                'app-id': () => true
            }
        })
// 6- Persist the url, since we are going to call it multiple times
            .persist()
// 7- Define the URI with the request query
            .get(`/data/v1/user?page=0&limit=50`)
// 8- Mock the response with 200 status and the results from 1st request
            .reply(200, responseForPage0)
// 9- Render the custom hook, using renderHook from React-Testing-Library
        const { result, waitFor } = renderHook(() => useUsersQuery(), { wrapper });

// 10- Wait for the request to be success, otherwise it will fail the test.
        await waitFor(() => result.current.isSuccess);
// 11- Comparing the results
        expect(result.current.data?.pages[0]).toStrictEqual({ results: responseForPage0.data, next: 1 });
    });
});

Here’s the description of what’s implemented in the file:

  1. Create a new QueryClient instance with retry = false, because React-query is defaulted to three retries with exponential backoff, which means that our tests are likely to timeout if we want to test an erroneous query.
  2. We did create a custom wrapper that builds the QueryClient and QueryClientProvider. This helps to ensure that our test is completely isolated from any other tests.
  3. Create a test suite.
  4. Create nock request interceptor.
  5. Mocking the ‘app-id’ header to return true, as we don’t need to put the actual header value, we can mock it to return true/false.
  6. Persist the URI, since we are going to call it multiple times with different request query parameters.
  7. Define the URI with the request query (Note: the page parameter value is 0).
  8. Mock the response with 200 status code and the results from 1st request (we have those results from part1).
  9. Render the custom hook, using renderHook from React-Testing-Library.
  10. Wait for the request to be success, otherwise it will fail the test.
  11. Comparing the results coming from the mocked api call, with our predefined results.

Now running the tests from the terminal and it should go green!

Now let’s add tests to lazy load page 2 and page 3

import { renderHook } from '@testing-library/react-hooks';
import nock from 'nock';
import { ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { responseForPage0, responseForPage1, responseForPage2 } from '../fixtures';
import { useUsersQuery } from '../useInfiniteQuery';

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

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

describe('useUsersQuery', () => {
    it('fetches the users list', async () => {
        nock('https://dummyapi.io', {
            reqheaders: {
                'app-id': () => true
            }
        })
            .persist()
            .get(`/data/v1/user?page=0&limit=50`)
            .reply(200, responseForPage0)

        const { result, waitFor } = renderHook(() => useUsersQuery(), { wrapper });
        await waitFor(() => result.current.isSuccess);
        expect(result.current.data?.pages[0]).toStrictEqual({ results: responseForPage0.data, next: 1 });

        // Calling the next page=1 and with mocked data from page1
        nock('https://dummyapi.io')
            .persist()
            .get(`/data/v1/user?page=1&limit=50`)
            .reply(200, responseForPage1);

        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 },
        ]);

        // Calling the next page=2 and with mocked data from page2
        nock('https://dummyapi.io')
            .persist()
            .get(`/data/v1/user?page=2&limit=50`)
            .reply(200, responseForPage2);

        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 },
        ]);
    });
});

There you go! Running the tests again should result in 100% coverage for this file, as shown:

That’s It!

Full source code: use-infinite-query.

Part1: 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: