使用Jest模拟add函数时遭遇TypeError错误求助
解决Jest模拟函数时出现TypeError: mockImplementation is not a function的问题
这个错误的核心是math.add并非有效的Jest mock函数,因此没有mockImplementation方法。问题根源在于你使用了从@jest/globals导入的jest对象来创建mock——jest.mock会被Jest自动提升到文件顶部执行,此时局部导入的jest还未初始化,导致jest.fn()生成的不是标准的mock函数。
方案1:使用全局Jest对象,移除局部导入
删除测试文件中从@jest/globals导入的jest,直接使用Jest全局提供的jest对象:
// myModule.test.js import * as math from '../math'; import { multiplyAndAdd } from '../myModule'; // Mock the 'add' function jest.mock('../math', () => ({ ...jest.requireActual('../math'), // 保留其他函数的原始实现 add: jest.fn(), })); describe('multiplyAndAdd', () => { it('multiplies and adds using the mock add function', () => { // 设置mock实现 math.add.mockImplementation((a, b) => { console.log("Fake calling..."); return a + b; }); const result = multiplyAndAdd(2, 3, 4); expect(result).toBe(20); // 可选:验证add函数的调用情况 expect(math.add).toHaveBeenCalledWith(2, 3); }); });
方案2:使用jest.spyOn替代手动mock模块
这种方式更灵活,无需提前mock整个模块,仅在测试用例中单独mock目标函数:
// myModule.test.js import * as math from '../math'; import { multiplyAndAdd } from '../myModule'; describe('multiplyAndAdd', () => { it('multiplies and adds using the mock add function', () => { // 监听add函数并替换为mock实现 const addMock = jest.spyOn(math, 'add').mockImplementation((a, b) => { console.log("Fake calling..."); return a + b; }); const result = multiplyAndAdd(2, 3, 4); expect(result).toBe(20); expect(addMock).toHaveBeenCalledWith(2, 3); // 测试结束后恢复原始实现,避免影响其他测试用例 addMock.mockRestore(); }); });
内容的提问来源于stack exchange,提问作者DosadoJr
相关产品推荐
相关产品推荐

