首页 > 解决方案 > Redux 单元测试操作我收到错误:expect(received).toEqual(expected) // 深度相等

问题描述

我正在尝试使用 jest 和 react-testing-library 为 Redux action.test.js 运行单元测试。

/src/store/actions/index.js

import actionTypes from '../ActionTypes';

export const setLoader = (value, errorMessage = '') => ({
  type: actionTypes.SET_LOADER,
  status: value,
  errorMessage,
});

/src/store/ActionsTypes.js

const actionTypes = {
  SET_LOADER: 'SET_LOADER'  
};

export default actionTypes;

在测试文件中,这是我的测试的一部分:

import * as actions from '../index';

describe('ACTIONS', () => {

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

我收到了这个错误:expect(received).toEqual(expected) // 深度相等

  ● ACTIONS › should create an actions with correct type

    expect(received).toEqual(expected) // deep equality

    - Expected  - 0
    + Received  + 2

      Object {
    +   "errorMessage": "",
    +   "status": undefined,
        "type": "SET_LOADER",
      }

对代码的任何更正都会非常有帮助谢谢!

新的更新

当我设置托盘时,errorMessage 如下所述:

expect(actions.setLoader()).toEqual({ type: 'SET_LOADER', errorMessage: 'message'});

我得到了一个更奇怪的错误:

    - Expected  - 1
    + Received  + 2

      Object {
    -   "errorMessage": "message",
    +   "errorMessage": "",
    +   "status": undefined,
        "type": "SET_LOADER",
      }

标签: reactjsunit-testingreduxjestjsreact-testing-library

解决方案


您的setLoader操作将errorMessage属性设置为""并将status属性设置为undefined;但是,您的断言没有考虑这些属性。您可以将这些属性添加到正在比较的对象中toEqual,或者您可以验证该type属性是否存在"SET_LOADER"- 这完全取决于您。


推荐阅读