You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 00:45:06