我有一个Dashboard
包含子组件的组件,例如Child
它使用 react-query。
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);
测试片段:
const queryClient = new QueryClient();
const { getByTestId, getByRole } = render(
<IntlProvider locale="en" messages={messages}>
<QueryClientProvider client={queryClient}>
<Dashboard />
</QueryClientProvider>
</IntlProvider>,
);
我阅读了有关测试的文档:
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,
);
}
这就是所谓的:
const { data, error, isFetching, isError } = usePosts({
rqKey,
url,
extraConfig,
});
根据您的回答,我应该创建一个单独的功能:
async () => {
const result = await window.fetch(url, options);
const data = await result.json();
return data;
},
例如
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,
);
}
然后在测试中模拟它。
如果我这样做,我将如何访问: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();
}
然后用作:
const { isLoading, error, data, isError } = useQuery(
[rqKey, { url, options }],
useFetch,
extraConfig,
);
所有作品。
在Dashboard
测试中,我然后执行以下操作:
import * as useFetch from ".";
和
jest.spyOn(useFetch, "useFetch").mockResolvedValue(["asdf", "asdf"]);
和
render(
<IntlProvider locale="en" messages={messages}>
<QueryClientProvider client={queryClient}>
<Dashboard />
</QueryClientProvider>
</IntlProvider>,
);
然后返回:
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,