T
TanStack•3y ago
rival-black

:white_check_mark: How to tests calls to query client passed in function?

Example method
export function SetDoots(dootlist: string[], queryClient: QueryClient): void {
for (let i = 0; i <= dootlist.length; i++) {
queryClient.setQueryData([dootlist[i]], dootlist[i]);
}
}
export function SetDoots(dootlist: string[], queryClient: QueryClient): void {
for (let i = 0; i <= dootlist.length; i++) {
queryClient.setQueryData([dootlist[i]], dootlist[i]);
}
}
6 Replies
rising-crimson
rising-crimson•3y ago
Hi 👋 You'd typically create a mock version of the queryClient and pass that as the argument under test and assert on it being called with whatever you expect
rival-black
rival-blackOP•3y ago
Nevermind. Good old
const spy = jest.spyOn(client, "setQueryData");
...
expect(spy).not.toHaveBeenCalled();
const spy = jest.spyOn(client, "setQueryData");
...
expect(spy).not.toHaveBeenCalled();
do the trick.
rising-crimson
rising-crimson•3y ago
You can spy, although dependency injection is a wonderful thing and you could easily pass a mock in yourself - up to you 🙂
rival-black
rival-blackOP•3y ago
Do you know is there any decent example of testing complex component with react query?
rival-black
rival-blackOP•3y ago
Thanks, I'm not seen second one.
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { screen } from "@testing-library/react";

import { render } from "../../test-utils/customRender";
import Login from "./Login";

describe("Login", () => {
test("renders Login component", async () => {
const client = new QueryClient();
const r = {
state: {},
title: "",
location: "/login",
};

render(
<QueryClientProvider client={client}>
<Login />
</QueryClientProvider>,
{ route: r }
);

expect(screen.getByText("Login"));
});
});
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { screen } from "@testing-library/react";

import { render } from "../../test-utils/customRender";
import Login from "./Login";

describe("Login", () => {
test("renders Login component", async () => {
const client = new QueryClient();
const r = {
state: {},
title: "",
location: "/login",
};

render(
<QueryClientProvider client={client}>
<Login />
</QueryClientProvider>,
{ route: r }
);

expect(screen.getByText("Login"));
});
});
Just tests here on this level, and seem to be I need to learn more about hooks.

Did you find this page helpful?