Integrate testing for react-query with testing-library
Asked Answered
L

2

7

Aim

I am building a NextJS application that uses react-query to fetch data.

I am now trying to implement a testing framework. However, when I run yarn test I get the error below. From the react-query docs, I understand that error typically relates to circumstances where <QueryClientProvider> has not been included in _app.js.

I suspect that I need to introduce some 'mock data' for react-query in index.test.js but haven't been able to find documentation on how to do so.

Error

No QueryClient set, use QueryClientProvider to set one

Code

/tests/index.test.js

import { render, screen } from '@testing-library/react';

import Home from '../pages/index';

describe('Home', () => {
    it('renders without crashing', () => {
        render(<Home />);

        expect(
            screen.getByRole('heading', { name: 'Welcome to Next.js!' })
        ).toBeInTheDocument();
    });
});

/pages/index.js

import Link from 'next/link';
import { Button } from 'antd';
import { useQuery } from 'react-query';

import { readUserRole } from '../lib/auth';
import NewBriefButton from '../components/Buttons/NewBriefButton';
import NewJobButton from '../components/Buttons/NewJobButton';
import NewClientButton from '../components/Buttons/NewClientButton';

export default function Home() {
    const userRoleQuery = useQuery('userRole', readUserRole);

    const { status, data } = userRoleQuery;

    if (status === 'error') {
        return <p>error...</p>;
    }

    if (status === 'loading') {
        return <p>loading...</p>;
    }

    return (
        <div>
            <h1>Home page</h1>
            {data === 'Manager' && (
                <>
                    <Button type='primary'>
                        <Link href='/assets/upload'>Upload Assets</Link>
                    </Button>
                    <NewBriefButton />
                    <NewJobButton />
                    <NewClientButton />
                </>
            )}
        </div>
    );
}

/pages/_app.js

import { QueryClient, QueryClientProvider } from 'react-query';
import { Hydrate } from 'react-query/hydration';

import Layout from '../components/Layout';
import AuthContextProvider from '../context/AuthContext';
import { GlobalStyles } from '../styles';

import 'antd/dist/antd.css';
import 'react-quill/dist/quill.snow.css';

const queryClient = new QueryClient();

export default function MyApp({ Component, pageProps }) {
    return (
        <AuthContextProvider>
            <QueryClientProvider client={queryClient}>
                <Hydrate state={pageProps.dehydratedState}>
                    <GlobalStyles />
                    <Layout>
                        <Component {...pageProps} />
                    </Layout>
                </Hydrate>
            </QueryClientProvider>
        </AuthContextProvider>
    );
}
Lear answered 13/1, 2021 at 0:26 Comment(0)
P
21

As the error suggests, you need to wrap the component you are mounting in your test in a QueryClientProvider as well:

describe('Home', () => {
    const queryClient = new QueryClient();
    it('renders without crashing', () => {
        render(
            <QueryClientProvider client={queryClient}>
                <Home />
            </QueryClientProvider>
        );

        expect(
            screen.getByRole('heading', { name: 'Welcome to Next.js!' })
        ).toBeInTheDocument();
    });
});

I would create a new Provider for each test to keep them isolated.

Pinky answered 13/1, 2021 at 6:33 Comment(0)
R
0

Another case can be that you're using a hook that uses the query client in your app. If so, make sure to mock that hook using the following pattern:

jest.mock(<the url of the hook>, () => ({
  <your hook's name>: jest.fn(<a callback that retuns what your hook retuns>),
}));
Reluct answered 29/3, 2023 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.