2017-02-19 49 views
3

我测试这个减速机:Jest.js测试没通过预期时/接收的值是对象

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)); 
}); 

的问题是,我的测试失败与Compared values have no visual difference备注如果我删除JSON.stringify()调用 - 我得到的比较对象与对象由于参考引起一些问题,但我必须使用JSON.stringify()或循环通过对象键来比较它们每次?

回答

5

我在回答我自己的问题。

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

总之,您不必使用JSON.stringify()并且Jest通过对象键,您只需使用正确的相等测试方法。

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