使用 React Hook 从笑话模拟返回数组

问题描述 投票:0回答:2

我正在尝试为自定义钩子创建一个模拟,该钩子利用 useEffect 和 use/createContext 并最终仅返回如下所示的内容:

[{ users: 0, hoursTested: 0, testDrives: 0 }, null];

我的代码如下:

import React from "react";
import { render, screen } from "@testing-library/react";
import BetaResults from "./BetaResults";

var mockResults = [{ users: 0, hoursTested: 0, testDrives: 0 }, null];
jest.mock("services/EAPStats/useEAPStats", () => {
  console.log("In Mock");
  return jest.fn(() => {
    console.log("In jest.fn");
    console.log("mock results", mockResults);
    return mockResults;
  });
});
test("renders BetaResults", async () => {
  mockResults = [{ users: 10, hoursTested: 10, testDrives: 10 }, undefined];
  render(<BetaResults />);
  expect(screen.getAllByTestId("BetaResultsHeaderText").length).toEqual(1);
});

当我执行测试时,我收到此错误:

Error: Uncaught [TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))]

执行永远不会到达 jest.fn 定义的函数。我忽略了什么?

reactjs jestjs react-hooks react-testing-library
2个回答
0
投票

尝试以下操作:

jest.mock('services/EAPStats/useEAPStats', () => ({
  __esModule: true,
  default: () => mockResults,
});

-1
投票

因此,我最终选择了一条不同的路线,并认为我应该发布我为那些难以围绕 React hooks 和 fetch 调用实施测试的其他人所做的事情。我没有做所有嘲笑的事情,而是选择了 msw,它更干净。下面是代码:

import React from "react";
import { render, screen, waitFor } from "@testing-library/react";
import BetaResults from "./BetaResults";
import { rest } from "msw";
import { setupServer } from "msw/node";

const server = setupServer(
  rest.get("/api/EAPStats.json", (req, res, ctx) => {
    return res(ctx.json({ users: 10, hoursTested: 1000, testDrives: 100 }));
  })
);

beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test("renders BetaResults", async () => {
  render(<BetaResults />);
  // Wait for the hook to fire and retrieve data. Initial render is loading component.
  await waitFor(() => screen.getByTestId("resultsBackground"));
  expect(screen.getByTestId("hoursTested").innerHTML).toEqual("1000");
  expect(screen.getByTestId("users").innerHTML).toEqual("10");
  expect(screen.getByTestId("testDrives").innerHTML).toEqual("100");
});

非常简单且容易了解如何对此进行扩展。

© www.soinside.com 2019 - 2024. All rights reserved.