I have a Dashboard component which contains a child component, e.g. Child which makes uses of react-query.
I have an existing unit test for the Dashboard component which started to fail, error being:
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);
Snippet from the test:
const queryClient = new QueryClient();
const { getByTestId, getByRole } = render(
<IntlProvider locale="en" messages={messages}>
<QueryClientProvider client={queryClient}>
<Dashboard />
</QueryClientProvider>
</IntlProvider>,
);
I read the documentation about testing:
https://react-query.tanstack.com/guides/testing#our-first-test
But I don't want to necessarily want to use renderHook as I am not interested in the result.
EDIT:
The Child component is using a function:
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,
);
}
Which is called as such:
const { data, error, isFetching, isError } = usePosts({
rqKey,
url,
extraConfig,
});
From your answer, I should be creating a separate function of:
async () => {
const result = await window.fetch(url, options);
const data = await result.json();
return data;
},
e.g.
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,
);
}
And then mock it in the test.
If I do that how would I then get access to: error, isFetching, isError
As usePosts() will now return a Promise<QueryObserverResult<unknown, unknown>>
EDIT 2:
I tried simplifying my code:
export async function useFetch({ queryKey }: any) {
const [_key, { url, options }] = queryKey;
const res = await window.fetch(url, options);
return await res.json();
}
Which is then used as:
const { isLoading, error, data, isError } = useQuery(
[rqKey, { url, options }],
useFetch,
extraConfig,
);
All works.
In the Dashboard test, I then do the following:
import * as useFetch from ".";
and
jest.spyOn(useFetch, "useFetch").mockResolvedValue(["asdf", "asdf"]);
and
render(
<IntlProvider locale="en" messages={messages}>
<QueryClientProvider client={queryClient}>
<Dashboard />
</QueryClientProvider>
</IntlProvider>,
);
Which then returns:
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,