mac*_*bem 8 unit-testing javascript-objects jestjs redux
我正在测试这个减速器:
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;
Run Code Online (Sandbox Code Playgroud)
通过这个测试:
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) );
});
Run Code Online (Sandbox Code Playgroud)
问题是Compared values have no visual difference如果我删除了JSON.stringify()调用,我的测试会失败并带有注释- 我认为将对象与对象进行比较会因为引用而产生一些问题,但我是否必须使用JSON.stringify()或循环对象键来每次比较它们?
mac*_*bem 12
我在回答我自己的问题.
该.toBe方法测试exact(===)相等性.为了比较对象,您必须使用.toEqual对每个对象键/数组索引进行递归检查的方法,具体取决于您的数据类型.
总之,您不必使用JSON.stringify()和Jest为您完成对象键,您只需使用正确的相等测试方法.
资料来源:https://facebook.github.io/jest/docs/using-matchers.html#content
| 归档时间: |
|
| 查看次数: |
9972 次 |
| 最近记录: |