目标
我正在构建一个 NextJS 应用程序,它使用 react-query 来获取数据。
我现在正在尝试实现一个测试框架。但是,当我运行时,yarn test
我收到以下错误。从 react-query 文档中,我了解到错误通常与<QueryClientProvider>
未包含在_app.js
.
我怀疑我需要为 react-query 引入一些“模拟数据”,index.test.js
但无法找到有关如何执行此操作的文档。
错误
No QueryClient set, use QueryClientProvider to set one
代码
/测试/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>
);
}