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

使用Jest编写Redux action单元测试出现toEqual深度匹配错误

Redux Action单元测试匹配错误修复方案

错误原因

你定义的setLoader action creator 返回的对象固定包含type、status、errorMessage三个字段,之前的测试用例存在两个问题:

  • 调用setLoader时没有传入任何参数,第一个入参value为undefined,对应返回值的status字段就是undefined;第二个入参errorMessage有默认值空字符串,对应返回值的errorMessage为""
  • toEqual是深度全量匹配,你写的预期对象要么缺了status、errorMessage字段,要么errorMessage填了错误的预期值,导致匹配失败

正确修复方案

根据你的测试场景选择对应写法即可:

场景1:测试无参数调用的返回结果

如果要验证不传参数调用的返回值,测试代码改为:

it('should create an action with correct type when no params are passed', () => {
  expect(actions.setLoader()).toEqual({
    type: 'SET_LOADER',
    status: undefined,
    errorMessage: ''
  });
})

更规范的写法是在测试文件导入actionTypes,用actionTypes.SET_LOADER代替硬编码的字符串,后续修改action类型值时无需同步修改测试代码。

场景2:测试传参调用的返回结果

如果要验证传参后的返回值,调用时传入对应参数即可:

it('should create an action with correct payload when params are passed', () => {
  const testStatus = true;
  const testError = 'load failed';
  expect(actions.setLoader(testStatus, testError)).toEqual({
    type: 'SET_LOADER',
    status: testStatus,
    errorMessage: testError
  });
})

场景3:只需验证部分字段

如果只需要校验type字段是否正确,不需要关心其他字段,可使用expect.objectContaining做部分匹配:

it('should create an action with correct type', () => {
  expect(actions.setLoader()).toEqual(expect.objectContaining({
    type: 'SET_LOADER'
  }));
})

内容的提问来源于stack exchange,提问作者Ivan K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:09:03