我有这个 React.js 应用程序,它是一个简单的购物车应用程序。 https://codesandbox.io/s/znvk4p70xl
问题是我试图使用 Jest
和 Enzyme
对应用程序的 state
进行单元测试,但它似乎不起作用。这是我的 Todo.test.js
单元测试:
import React from 'react';
import { shallow } 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 = shallow(<Todo cart={cart} />);
const firstInput = wrapper.find('input').at(0);
firstInput.simulate('change', { target: { value: 'Pink' } });
const firstCost = wrapper.find('input').at(1);
firstCost.simulate('change', { target: { value: 200 } });
const submitButton = wrapper.find('button').at(0);
submitButton.simulate('click');
console.log(wrapper.state());
});
最后的console.log
显示0
。这很奇怪,因为即使在模拟
点击之后,它应该大于0
。
我做错了什么?
最佳答案
据我了解,您的点击代码没有设置任何状态,它只是
更新变量 {totalCost}
您应该更新状态的位置
以便获取更新状态值。
或者
您可以通过首先更新测试类中的状态来检查是否 您的状态是否更新:
wrapper.setState({
totalCost: 20
});
让我知道你的想法。
关于javascript - React 16 状态测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50223727/