我目前正在以這種方式模擬 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

那么,如果我需要多次模擬該函式以便我可以看到我的 React 組件將顯示什么,那么處理這個問題的方法是什么?
我知道我可以創建多個檔案,例如SectionCourses-V1.test.tsx,SectionCourses-V2.test.tsx...但是有這么多檔案并不理想
注意:這不是Jest 的副本——模擬一個在 React 組件中呼叫的函式
uj5u.com熱心網友回復:
您可以鏈接 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: [],
}))
}
uj5u.com熱心網友回復:
您可以在測驗方法本身內部移動模擬的實作,以便每個測驗方法都在提供的模擬實作上作業。
it("not found", async () => {
jest.mock("@myORG/axiosWrapperReactQuery", () => {
const original = jest.requireActual("@myORG/axiosWrapperReactQuery");
return {
...original,
getAllCourses: jest.fn().mockImplementation(() => ({
isLoading: false,
typedData: [],
})),
};
});
const { findByText } = render(
<QueryClientProvider client={queryClient}>
<SectionCourses />
</QueryClientProvider>
);
const firstCourse = await findByText("No courses found");
expect(firstCourse).toBeInTheDocument();
});
it("is loading", async () => {
jest.mock("@myORG/axiosWrapperReactQuery", () => {
const original = jest.requireActual("@myORG/axiosWrapperReactQuery");
return {
...original,
getAllCourses: jest.fn().mockImplementation(() => ({
isLoading: true, // This changed to true
typedData: [],
})),
};
});
const { findByText } = render(
<QueryClientProvider client={queryClient}>
<SectionCourses />
</QueryClientProvider>
);
const firstCourse = await findByText("Loading...");
expect(firstCourse).toBeInTheDocument();
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470390.html
