Jest自动mock ES6类时报错received must be a mock or spy函数如何解决
错误原因
你当前的报错是因为run是DetectFibonacciUseCase的实例方法,不是类的静态方法:
- Jest自动mock ES6类后,
DetectFibonacciUseCase会变成一个mock构造函数,本身不会自带run属性,所以你直接访问DetectFibonacciUseCase.run拿到的就是undefined,自然不符合toHaveBeenCalled要求传入mock/spy函数的规则 - 你业务代码里是先
new DetectFibonacciUseCase()生成实例,再调用实例上的run方法,所以你需要监听的是实例上的run方法,而不是类本身的属性
修复方案
修改你的测试用例代码,提前mock类的实现,把实例的run方法替换成你自定义的mock函数,之后直接断言这个mock函数即可:
import { render, fireEvent } from "@testing-library/react"; import Grid from "../../components/Grid"; import DetectFibonacciUseCase from "../../useCases/DetectFibonacciUseCase"; jest.mock("../../useCases/DetectFibonacciUseCase"); describe("GridComponent", () => { test("Should've called the run method when the callback is executed", () => { // 提前定义mock的run方法,可根据业务需要自定义返回值 const mockRun = jest.fn().mockReturnValue([]); // 给mock构造函数设置实现,返回带mockRun方法的实例 DetectFibonacciUseCase.mockImplementation(() => ({ run: mockRun })); const { getByTestId } = render(<Grid />); const firstCellButton = getByTestId("cell-testid-0-0"); fireEvent.click(firstCellButton); // 断言自定义的mockRun被调用即可 expect(mockRun).toHaveBeenCalled(); // 有需要还可以验证传参是否正确,示例: // expect(mockRun).toHaveBeenCalledWith(expect.any(Array)) }); });
补充说明
如果你使用TypeScript,需要给DetectFibonacciUseCase加上as jest.Mock的类型声明,用来告知TS当前类已经被处理为mock构造函数,可以安全调用mockImplementation方法,纯JS项目可以省略该类型声明。
内容的提问来源于stack exchange,提问作者Alberto Herrera Vargas
相关产品推荐
相关产品推荐

