使用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.
相关产品推荐
相关产品推荐

