反应.js - 模拟酶的点击



我有这个 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 } ]

酶的simulate正在你的Todo组件上寻找一个onChange事件,但它没有找到。 您没有将onChange指定为道具,因此它没有触发是有道理的。 将onChange道具连接到组件(如果这是您想要测试它的方式)。 从文档中:

即使名称暗示这模拟了实际事件, .simulate() 实际上将针对组件的 prop 基于 你给它的事件。例如,.simulate('click') 实际上会得到 onClick 道具并调用它。

您正在尝试模拟对具有类addtocart的元素的单击。但是,您没有具有类addtocart的元素。添加按钮的元素 ID 为submit

更改此设置:

const submitButton = wrapper.find('.addtocart');

对此:

const submitButton = wrapper.find('#submit');

查看Todo代码后:

<input id="itemname" name="name" ref={this.nameRef} className="form-control" type="text" placeholder="Add item to List" />

<input name="cost" id="itemcost" ref={this.costRef} className="form-control" size="5" type="text" placeholder="Cost" />

我认为wrapper.find('.cost')行不通。我建议你做wrapper.find('#cost')

最新更新