当 expected/received 值是对象时,Jest.js 测试未通过

Jest.js tests don't pass when expected/received values are objects

我正在测试这个减速器:

const todo = (state = {}, action) => {
  switch(action.type) {
    case 'ADD_TODO':
      return {
        id: action.id,
        text: action.text,
        completed: false
      }
    case 'TOGGLE_TODO':
      if(state.id !== action.id) {
        return state;
      }
      return {...state, completed: !state.completed};

    default:
      return state;
  }
}

const todos = (state = [], action) => {
  switch(action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        todo(undefined, action)
      ]
    case 'TOGGLE_TODO':
      return state.map(item => todo(item, action));
    default:
      return state;
  }
}

export default todos;

通过此测试:

import todos from './todos';

test('creates a new todo', () => {
  const stateBefore = [];
  const action = {
    type: 'ADD_TODO',
    id: 0,
    text: 'test'
  };
  const stateAfter = [{
    id: 0,
    text: 'test',
    completed: false
  }];

  expect( JSON.stringify( todos(stateBefore, action) ) ).toBe( JSON.stringify(stateAfter) );
});

问题是,如果我删除 JSON.stringify() 调用,我的测试会失败并显示 Compared values have no visual difference 注释 - 我知道将一个对象与另一个对象进行比较会因为引用而产生一些问题,但是我这样做吗?必须使用 JSON.stringify() 或遍历对象键来每次比较它们?

我在回答我自己的问题。

.toBe 方法测试精确 (===) 相等性。为了比较对象,您必须使用 .toEqual 方法,该方法根据您的数据类型对每个对象键/数组索引进行递归检查。

总之,您不必使用 JSON.stringify() 和 Jest 为您检查对象键,您只需要使用正确的相等性测试方法。

来源:https://facebook.github.io/jest/docs/using-matchers.html#content