next.js 使用测试库集成react-query测试

raogr8fs  于 2023-03-29  发布在  React
关注(0)|答案(2)|浏览(141)

目标

我正在构建一个NextJS应用程序,它使用react-query来获取数据。
我现在试图实现一个测试框架。然而,当我运行yarn test时,我得到了下面的错误。从react-query文档中,我了解到该错误通常与<QueryClientProvider>未包含在_app.js中的情况有关。
我怀疑我需要在index.test.js中为react-query引入一些“模拟数据”,但还没有找到如何这样做的文档。

错误

No QueryClient set, use QueryClientProvider to set one

代码

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

eimct9ow1#

如错误所示,您还需要将测试中挂载的组件 Package 在QueryClientProvider中:

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

我会为每个测试创建一个新的Provider,以保持它们的隔离。

dtcbnfnu

dtcbnfnu2#

另一种情况是,你在应用中使用了一个使用查询客户端的钩子。如果是这样,请确保使用以下模式模拟该钩子:

jest.mock(<the url of the hook>, () => ({
  <your hook's name>: jest.fn(<a callback that retuns what your hook retuns>),
}));

相关问题