Jest Mock检查时显示undefined问题排查求助
解决Jest Mock自定义模块时出现Undefined的问题
这种情况我之前也碰到过,大概率是mock的写法或者模块导入的细节没处理对。咱们一步步排查解决:
1. 先检查模块路径是否正确
Jest对自定义模块的相对路径非常敏感,哪怕差一个层级或者拼写错误,都会导致mock找不到目标模块,最终返回undefined。
比如你的foo模块在../utils/foo.js,那jest.mock的参数必须严格匹配这个路径:
// 正确:路径和导入被测模块时的路径一致 jest.mock('../utils/foo');
可以在测试里临时打印导入的模块,确认路径是否正确:
import * as foo from '../utils/foo'; console.log(foo); // 如果输出undefined,肯定是路径错了
2. 匹配模块的导出结构
如果你的foo模块是命名导出,mock对象必须包含对应的命名属性;如果是默认导出,mock要对应default字段。
情况A:foo是命名导出
假设foo.js的代码是:
// foo.js export const targetMethod = () => { /* 实际逻辑 */ };
测试里的mock要这样写:
// 测试文件 jest.mock('./foo', () => ({ // 必须和命名导出的字段一致 targetMethod: jest.fn() })); import { targetMethod } from './foo'; import { testedFunction } from './moduleUnderTest'; test('验证调用了targetMethod', () => { testedFunction(); expect(targetMethod).toHaveBeenCalled(); });
情况B:foo是默认导出
如果foo.js是默认导出一个对象:
// foo.js export default { targetMethod: () => { /* 实际逻辑 */ } };
那mock要包含default字段:
jest.mock('./foo', () => ({ default: { targetMethod: jest.fn() } })); // 或者用jest.spyOn更直观 import foo from './foo'; jest.spyOn(foo, 'targetMethod').mockImplementation(() => {});
3. 确保mock工厂函数正确返回对象
很多时候mock变成undefined,是因为jest.mock的工厂函数漏了return,或者返回的结构不对。
❌ 错误写法(漏了return):
jest.mock('./foo', () => { targetMethod: jest.fn() // 这里没有return,相当于返回undefined });
✅ 正确写法:
jest.mock('./foo', () => ({ targetMethod: jest.fn() })); // 或者用箭头函数隐式返回 jest.mock('./foo', () => ({ targetMethod: jest.fn() }));
4. 检查模块导入顺序
虽然Jest会自动把jest.mock提升到文件顶部,但如果你的测试里用了require而不是ES模块的import,或者有动态导入的情况,可能会导致被测模块在mock生效前就加载了。
确保你的require顺序正确:
// 正确顺序:先mock,再require jest.mock('./foo'); const { testedFunction } = require('./moduleUnderTest'); const { targetMethod } = require('./foo');
最后调试技巧
如果还是找不到问题,可以在测试里打印导入的foo模块,看看实际结构是什么:
import * as foo from './foo'; console.log('Mocked foo:', foo);
如果输出是{}或者undefined,那要么路径错了,要么导出结构没匹配对;如果有内容但方法不是jest.fn(),那就是mock的写法有问题。
内容的提问来源于stack exchange,提问作者springloaded
相关产品推荐
相关产品推荐

