testing-react-query's People
Forkers
willnguyen1312 mrtousif dheemanthp ziphr macro516 dykim-haezoom frivolta vangelov tiagonevestia jordybastien kcharaa tskim-newin isaacjoh github-julien-bistoquet stfny222 goldpot carlocarpio dapunzalan morenar dolphorama danr-za arnassavickas klaborda adamgibs devjunyg mdwatson90 edilbertorodriguezsantillana nguyenlam123 petitkriket amirulandalib birant pds0309 dannajo dilkax1023 asde29873012549testing-react-query's Issues
graphql tests
Would you please add an example for testing graphql?
Vitest Integration
Can you please do an example with the vitest library?
I am using vitest for testing. However, my tests do not return any outputs.
How to achieve in combination with generating snapshot?
how to test a react component that invokes refetch
Hey there,
I am using this library in a project at work and we have a component that uses useQuery, which will invoke the refetch() function when a refresh button is clicked.
In my unit tests I'd like to verify that a re-fetch occurs by checking that our loading screen is shown, however since our loading screen is only shown if isFetching is true this fails. This is because after the initial fetch sets isFetching to false, it stays false even after calling refetch.
I've only seen examples of how to test this scenario when testing the custom hook that wraps useQuery, but I don't want to test the hook, I want to test the component that is ingesting it.
React Query Test with MSW - renderHook result.current always returns null
I am trying to test my react query hook using msw but renderHook
's result
's current
value is always null. Why?
Note: the reason fetch
does not include a URL is because this is a Rails Propshaft app and React and Rails apps share the same port.
In the real app, everything works and the hook returns data just fine but not in the test.
followed your original tutorial
App.tsx
const App = () => {
const {
isLoading,
data,
error
} = useFetchAccounts();
if (isLoading) return "Loading...";
if (error) return "An error has occurred: " + error;
return (
<div>
{data?.map(item => (
<div key={item.id}>{item.value}</div>
))}
</div>
);
};
App.spec.tsx
const testQueryClient = new QueryClient({
defaultOptions: {
queries: {
retry: false
}
}
});
testQueryClient.setQueryDefaults(["accounts"], { retry: 5 });
describe("Accounts", () => {
it("renders accounts", async () => {
const { result } = renderHook(() => useFetchAccounts(), {
wrapper: () => (
<QueryClientProvider client={testQueryClient}>
<App />
</QueryClientProvider>
)
});
console.log("result", result);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
});
});
hooks.tsx
import { useQuery } from "@tanstack/react-query";
type FormattedAccount = {
id: number;
label: string;
};
const fetchAccount = async () => {
const res = await fetch("/api/accounts");
const accounts = await res.json();
console.log("accounts", accounts);
const formattedAccounts: FormattedAccount[] = [...accounts]?.map(
(option) => ({
id: option.id,
label: option.name,
})
);
console.log("formattedAccounts", formattedAccounts);
return formattedAccounts;
};
export const useFetchAccounts = () => {
return useQuery({
queryKey: ["accounts"],
queryFn: () => fetchAccount()
});
};
server.ts
import { setupServer } from "msw/node";
import { rest } from "msw";
export const handlers = [
rest.get("/api/accounts", (req, res, ctx) => {
const rres = res(ctx.status(200), ctx.json([{ id: 1, name: "Account 1" }]));
console.log("rres", rres);
return rres;
})
];
export const server = setupServer(...handlers);
jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
collectCoverage: true,
collectCoverageFrom: ["src/**/*.spec.{ts, tsx}"],
coverageDirectory: "coverage",
testEnvironment: "jsdom",
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
transform: {
"^.+\\.(ts|tsx)?$": "ts-jest"
}
};
jest.setup.ts
import "@testing-library/jest-dom";
import "whatwg-fetch";
import { server } from "./server";
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
export default global.matchMedia =
global.matchMedia ||
function (query) {
return {
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // deprecated
removeListener: jest.fn(), // deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn()
};
};
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. ๐๐๐
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google โค๏ธ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.