首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >“多次”模拟在反应性组件中使用的函数。

“多次”模拟在反应性组件中使用的函数。
EN

Stack Overflow用户
提问于 2022-05-02 05:30:48
回答 2查看 514关注 0票数 0

我目前正在以这样的方式在一个react项目中嘲弄一个内部依赖:

代码语言:javascript
运行
复制
import { QueryClient, QueryClientProvider } from "react-query";
import { render } from "@testing-library/react";
import SectionCourses from "./SectionCourses";

const queryClient = new QueryClient({});

jest.mock("@myORG/axiosWrapperReactQuery", () => {
  const original = jest.requireActual("@myORG/axiosWrapperReactQuery");
  return {
    ...original,
    getAllCourses: jest.fn().mockImplementation(() => ({
      isLoading: false,
      typedData: [],
    })),
  };
});

it("not found", async () => {
  const { findByText } = render(
    <QueryClientProvider client={queryClient}>
      <SectionCourses />
    </QueryClientProvider>
  );

  const firstCourse = await findByText("No courses found");
  expect(firstCourse).toBeInTheDocument();
});

它工作得很完美,但是当我试图在同一个文件中再次模拟依赖项时,它会失败。

代码语言:javascript
运行
复制
// ALL THE PREVIOUS CODE

jest.mock("@myORG/axiosWrapperReactQuery", () => {
  const original = jest.requireActual("@myORG/axiosWrapperReactQuery");
  return {
    ...original,
    getAllCourses: jest.fn().mockImplementation(() => ({
      isLoading: true, // This was changed to true
      typedData: [],
    })),
  };
});

it("is loading", async () => {
  const { findByText } = render(
    <QueryClientProvider client={queryClient}>
      <SectionCourses />
    </QueryClientProvider>
  );

  const firstCourse = await findByText("Loading...");
  expect(firstCourse).toBeInTheDocument();
});

似乎只需要最后一个jest.mock

那么,如果我需要多次模拟这个功能,以便我可以看到我的反应性组件将显示什么,那么如何处理这个问题呢?

我知道我可以创建多个文件,比如SectionCourses-V1.test.tsxSectionCourses-V2.test.tsx.但是有这么多文件并不理想

注意:这不是模仿一个在一个反应性组件中调用的函数。的副本

EN

Stack Overflow用户

回答已采纳

发布于 2022-05-02 08:18:35

您可以链接getAllCourses 开玩笑的医生的模拟实现。

尝尝这个,

代码语言:javascript
运行
复制
jest.mock("@myORG/axiosWrapperReactQuery", () => {
const original = jest.requireActual("@myORG/axiosWrapperReactQuery");
return {
  ...original,
  getAllCourses: jest.fn()
                 .mockImplementationOnce(() => ({
                             isLoading: false, // 1st call
                             typedData: [],
                 }))
                 .mockImplementationOnce(() => ({
                             isLoading: true, // 2nd call
                             typedData: [],
                 }))
}
票数 1
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72082655

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档