React-Query - 使用react-testing-library进行单元测试

Rob*_*ens 6 typescript reactjs react-testing-library react-query

我有一个Dashboard包含子组件的组件,例如Child它使用反应查询。

我有一个针对该Dashboard组件的现有单元测试,该测试开始失败,错误是:

TypeError: queryClient.defaultQueryObserverOptions is not a function

  38 |     const { locale } = React.useContext(LocaleStateContext);
  39 |     const options = getOptions(locale);
> 40 |     return useQuery(
     |            ^
  41 |         rqKey,
  42 |         async () => {
  43 |             const result = await window.fetch(url, options);
Run Code Online (Sandbox Code Playgroud)

测试片段:

const queryClient = new QueryClient();
const { getByTestId, getByRole } = render(
    <IntlProvider locale="en" messages={messages}>
        <QueryClientProvider client={queryClient}>
            <Dashboard />
        </QueryClientProvider>
    </IntlProvider>,
);
Run Code Online (Sandbox Code Playgroud)

我阅读了有关测试的文档:

https://react-query.tanstack.com/guides/testing#our-first-test

但我不想一定要使用,renderHook因为我对结果不感兴趣。

编辑:

Child组件正在使用一个函数:

export function usePosts({ rqKey, url, extraConfig }: CallApiProps) {
    const { locale } = React.useContext(LocaleStateContext);
    const options = getOptions(locale);
    return useQuery(
        rqKey,
        async () => {
            const result = await window.fetch(url, options);
            const data = await result.json();
            return data;
        },
        extraConfig,
    );
}
Run Code Online (Sandbox Code Playgroud)

这被称为:

const { data, error, isFetching, isError } = usePosts({
        rqKey,
        url,
        extraConfig,
    });
Run Code Online (Sandbox Code Playgroud)

根据你的回答,我应该创建一个单独的函数:

async () => {
            const result = await window.fetch(url, options);
            const data = await result.json();
            return data;
        },
Run Code Online (Sandbox Code Playgroud)

例如

export async function usePosts({ rqKey, url, extraConfig }: CallApiProps) {
    const { locale } = React.useContext(LocaleStateContext);
    const options = getOptions(locale);
    return useQuery(
        rqKey,
        await getFoos(url, options),
        extraConfig,
    );
}
Run Code Online (Sandbox Code Playgroud)

然后在测试中模拟它。

如果我这样做,我将如何访问:error, isFetching, isError

现在将usePosts()返回一个Promise<QueryObserverResult<unknown, unknown>>

编辑2:

我尝试简化我的代码:

export async function useFetch({ queryKey }: any) {
    const [_key, { url, options }] = queryKey;
    const res = await window.fetch(url, options);
    return await res.json();
}
Run Code Online (Sandbox Code Playgroud)

然后用作:

const { isLoading, error, data, isError } = useQuery(
    [rqKey, { url, options }],
    useFetch,
    extraConfig,
);
Run Code Online (Sandbox Code Playgroud)

所有作品。

Dashboard测试中,我然后执行以下操作:

import * as useFetch from ".";
Run Code Online (Sandbox Code Playgroud)

jest.spyOn(useFetch, "useFetch").mockResolvedValue(["asdf", "asdf"]);
Run Code Online (Sandbox Code Playgroud)

render(
        <IntlProvider locale="en" messages={messages}>
            <QueryClientProvider client={queryClient}>
                <Dashboard />
            </QueryClientProvider>
        </IntlProvider>,
    );
Run Code Online (Sandbox Code Playgroud)

然后返回:

TypeError: queryClient.defaultQueryObserverOptions is not a function

      78 |     const { locale } = React.useContext(LocaleStateContext);
      79 |     const options = getOptions(locale);
    > 80 |     const { isLoading, error, data, isError } = useQuery(
         |                                                 ^
      81 |         [rqKey, { url, options }],
      82 |         useFetch,
      83 |         extraConfig,
Run Code Online (Sandbox Code Playgroud)

Flo*_*Flo 4

您提到的文档页面解释了如何依赖 React Query 测试自定义挂钩。您是否正在使用基于 React Query 的自定义钩子,或者您只想测试使用 useQuery (React Query 提供的钩子)的组件?

如果您只想测试使用 useQuery 的 Child ,您应该模拟您的“请求函数”(返回 Promises 的函数,用作 useQuery 的第二个参数,并在没有任何提供程序的情况下渲染您的组件进行测试。

例如,假设在 Child 中你有

const foo = useQuery('key', getFoos, { // additional config here });
// foo is a QueryResult object (https://react-query.tanstack.com/reference/useQuery)
// so your usePost function will return a QueryResult as well
// foo.data holds the query results (or undefined)
// you can access to foo.error, foo.isFetching, foo.status...
// also note that extra parameter to be passed to your async function 
// should be part of the request key. Key should be an array :
// useQuery(['key', params], getFoos, { // additional config });
// so params object props will be passed as parameters for getFoos fucntion
// see https://react-query.tanstack.com/guides/query-keys#array-keys
Run Code Online (Sandbox Code Playgroud)

...并且 getFoos 定义path/to/file/defining/getFoos.ts

const getFoos = async (): Promise<string[]> => await fetch(...);
Run Code Online (Sandbox Code Playgroud)

...然后在 Child.test.tsx 中你可以做

import * as FooModule from 'path/to/file/defining/getFoos';

// this line could be at the top of file or in a particular test()
jest.spyOn(FooModule, 'getFoos').mockResolvedValue(['mocked', 'foos']);

// now in your Child tests you'll always get ['mocked', 'foos']
// through useQuery (in foo.data), but you'll still have to use https://testing-library.com/docs/dom-testing-library/api-async/#waitfor (mocked but still async)
// No need for QueryClientProvider in this case, just render <Child />
Run Code Online (Sandbox Code Playgroud)

回答:

尽管上面的答案帮助我朝正确的方向发展,但根本问题是我使用mockImplementation来提供上下文,然后使 QueryClientProvider 给出的上下文变得无用,例如

jest.spyOn(React, "useContext").mockImplementation(() => ({
    ...
}));
Run Code Online (Sandbox Code Playgroud)

我最终删除了模拟实现并在 QueryClientProvider 旁边添加到我的 UserStateContext.Provider 中并解决了问题:

render(
    <IntlProvider locale="en" messages={messages}>
        <UserStateContext.Provider value={value}>
            <QueryClientProvider client={queryClient}>
                <Dashboard />
            </QueryClientProvider>
        </UserStateContext.Provider>
    </IntlProvider>,
);
Run Code Online (Sandbox Code Playgroud)