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