我目前正在以这样的方式在一个react项目中嘲弄一个内部依赖:
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();
});它工作得很完美,但是当我试图在同一个文件中再次模拟依赖项时,它会失败。
// 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.tsx,SectionCourses-V2.test.tsx.但是有这么多文件并不理想
注意:这不是模仿一个在一个反应性组件中调用的函数。的副本
发布于 2022-05-02 08:18:35
您可以链接getAllCourses 开玩笑的医生的模拟实现。
尝尝这个,
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: [],
}))
}https://stackoverflow.com/questions/72082655
复制相似问题