我有这个 React.js 应用程序,它是一个简单的购物车应用程序。 https://codesandbox.io/s/znvk4p70xl
问题是我正在尝试使用 Jest 和 Enzyme 对应用程序的状态进行单元测试,但它似乎不起作用。这是我的 Todo.test.js 单元测试:
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Todo from '../components/Todo';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
test('Test it', async () => {
// Render a checkbox with label in the document
const cart = [
{ name: 'Green', cost: 4 },
{ name: 'Red', cost: 8 },
{ name: 'Blue', cost: 14 }
];
const wrapper = mount(<Todo cart={cart} />);
const firstInput = wrapper.find('.name');
firstInput.simulate('change', { target: { value: 'Pink' } });
const firstCost = wrapper.find('.cost');
firstCost.simulate('change', { target: { value: 200 } });
const submitButton = wrapper.find('.addtocart');
submitButton.simulate('click');
wrapper.update();
expect(wrapper.state('price')).toBe(26);
console.log(wrapper.state());
console.log(wrapper.props().cart);
});
当我运行测试时,当应添加项目 Pink 时,购物车仍然显示相同的内容。
当我在 addToCart 方法上模拟按钮单击时,怎么会出现这种情况?
PASS src/__tests__/todo.test.js
● Console
console.log src/__tests__/todo.test.js:32 { price: 26 }
console.log src/__tests__/todo.test.js:33 [ { name: 'Green', cost: 4 }, { name: 'Red', cost: 8 }, { name: 'Blue', cost: 14 } ]
请您参考如下方法:
Enzyme 的 simulate 正在您的 Todo 组件上查找 onChange 事件,但没有找到。您没有将 onChange 指定为 prop,因此它不会触发是有道理的。如果您想要测试它,请将 onChange 属性连接到您的组件。来自文档:
Even though the name would imply this simulates an actual event, .simulate() will in fact target the component's prop based on the event you give it. For example, .simulate('click') will actually get the onClick prop and call it.






