如何在Jest测试中正确Mock Lodash的get方法使其返回指定值
正确Mock Lodash get方法的方案
现有代码的问题点
- 断言逻辑错误:enzyme的
find方法无论是否匹配到组件,都会返回Wrapper对象,永远为真,无法判断组件是否真实渲染,需要调用.exists()方法做判断 - 组件查找方式不严谨:使用字符串
MyComponent查找组件容易匹配到名称相同的其他元素,建议直接导入组件实例进行匹配 - 全局方法拼写不一致:业务代码调用
window.getStatus(),测试代码中定义的是global.getState,拼写不匹配,容易埋下隐藏问题 - 可选优化:
mockReturnValueOnce只生效一次,如果组件渲染过程中get被调用多次,会出现返回值不符合预期的情况,可根据场景替换为mockReturnValue或者带参数校验的mockImplementation
修正后的测试代码
import get from 'lodash/get'; import MyComponent from '../../MyComponent'; // 导入组件用于精准查找 jest.mock('lodash/get'); global.getStatus = jest.fn(() => ({})); // 修正方法名和业务代码对齐 describe('Test', () => { const render = (props) => shallow( <A {...props} /> ); it('should not render MyComponent when get returns customValue', () => { get.mockReturnValue('customValue'); // 用mockReturnValue保证所有调用都返回指定值 const r = render({ someKey: 'someValue', }); // 正确断言:MyComponent不存在 expect(r.find(MyComponent).exists()).toBe(false); }); }
如果需要更精准的mock,只在匹配到指定参数时返回customValue,可以用mockImplementation:
get.mockImplementation((obj, path) => { if (path === "data.toJS()['base-path'].current['frame-name'].exclusions['period']") { return 'customValue'; } // 其他调用可以走原get逻辑,需要先导入原lodash/get方法 // return jest.requireActual('lodash/get')(obj, path); });
内容的提问来源于stack exchange,提问作者karvai
相关产品推荐
相关产品推荐

