尝试使用 jest 测试 React 组件。所以我有一个包含 3 个 it 块的描述块。假设我将一个 util 函数 useIsCarCostly 嘲笑为 true,但在第三个 it 块中我希望它为 false 以测试特定场景。我们如何模拟特定于 it 块的函数。
反应组件
import React from "react";
import { useIsCarDetailsEnabled } from "../../../utils/utils";
const CarSection = ({ car, dispatch }) => {
const isCarDetailsEnabled = useIsCarDetailsEnabled();
return isCarDetailsEnabled ? (
<div>
{car.isCarCostly() ? (
<h2>Expensive Car</h2>
) : (
<h2>Affordable Car</h2>
)}
</div>
) : null;
};
export default CarSection;
实用工具
const useIsCarDetailsEnabled = () => {
// Some business logic
return true;
};
export { useIsCarDetailsEnabled };
测试文件
import React from "react";
import CarSection from "../CarSection";
import Car from "../../types/Car";
import { render } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "react-query";
import { useIsCarDetailsEnabled } from "../../utils/utils";
const queryClient = new QueryClient();
jest.mock("../../utils/utils", () => ({
...jest.requireActual("../../utils/utils"),
useIsCarDetailsEnabled: jest.fn(() => false),
}));
describe('CarSection tests', () => {
let dispatchMock;
beforeEach(() => {
dispatchMock = jest.fn();
});
afterEach(() => {
jest.restoreAllMocks();
});
const renderComponent = () => {
return render(
<QueryClientProvider client={queryClient}>
<CarSection
car={new Car({ model: "Toyota", price: 30000 })}
dispatch={dispatchMock}
/>
</QueryClientProvider>
);
};
it('Check if component renders correctly when car details are not enabled', () => {
const { container } = renderComponent();
expect(container.firstChild).toBeNull();
});
it('Check if expensive car label renders if car is costly', () => {
// How to useIsCarDetailsEnabled as true here
jest.spyOn(Car.prototype, 'isCarCostly').mockReturnValue(true);
const { queryAllByText } = renderComponent();
const expensiveCarLabel = queryAllByText("Expensive Car");
expect(expensiveCarLabel.length).toBeGreaterThan(0);
});
});
您可以模拟一个模块,然后导入模拟的方法或对象,这为您提供了对可以动态更新的模拟的引用。
import { myFunction } from '~/myFile'
jest.mock(
'~/myFile',
() => ({ myFunction: jest.fn() })
)
describe('some behaviour', () => {
it('uses one mock value', () => {
myFunction.mockReturnValue('a')
// test here
})
it('uses another mock value', () => {
myFunction.mockReturnValue('b')
// test here
})
})