我是React的新手,并且在测试方面遇到一些问题。 我要在Github上Ryan Walsh最出色的学习者项目中添加测试List.test.js:https://github.com/r-walsh/react-unit-test-practice。
此submitToDo()测试通过:
功能:
submitToDo = text =>
this.setState(() => ({
toDos: [{ complete: false, text },
...this.state.toDos],
}));
测试:
it('adds new ToDo to state', () => {
const list = shallow(<List />);
list.setState({
toDos: [
{ complete: false, text: 'One'},
{ complete: true, text: 'Two'},
],
});
list.instance().submitToDo('Three');
expect(list.state().toDos.length).toBe(3);
expect(list.state().toDos[0].text).toBe('Three');
});
toggleCompletion测试未通过。调试器告诉我,调用toggleCompletion时,“文本”没有任何值。如果我从text参数中删除({}),则测试通过,但切换开关在浏览器中不再起作用。
功能:
toggleCompletion = ({text}) =>
this.setState(({ toDos }) => ({
toDos: toDos.map(
toDo =>
toDo.text === text ? { complete:
!toDo.complete, text } : toDo,),
}));
测试:
it('toggles completion', () => {
const list = mount(<List />);
list.setState({
toDos: [
{ complete: false, text: 'One'},
],
});
expect(list.state().toDos[0].complete).toBe(false);
list.instance().toggleCompletion('One');
// todo test fails, but this works in the browser
expect(list.state().toDos[0].complete).toBe(true);
});