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()
或循環通過對象鍵來比較它們每次?