English 中文(简体)
事实 与劳动和社会福利部进行的测试——结果结果总是使回报无效
原标题:React Query Test with MSW - renderHook result always returns null

我试图测试我的回答问询,使用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()
    };
  };
问题回答

本法典的作用

const { data} = useQuery({
      queryKey: ["bills"],
      queryFn: async () => await fetchItem("/bills"),
    });




相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签