我试图测试我的回答问询,使用ms,但renderHook
sresult
s 当前
。 价值永远无效。 为什么?
<<>Note/strong>: 理由fetch
不包括URL,因为这是一种铁路机车和反应器,铁路机在同一港口。
在实际评估中,所有工作都奏效,回归数据只微薄,而不是试样。
https://tkdodo.eu/blog/testing-react-query”rel=“nofollow noreferer”> 页: 1
https://codesand Box.io/s/blissful-dewdney-r6k4mm?file=/src/App.spec.tsx” rel=“nofollow noreferer”>reproducible砂箱
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()
};
};