React.js - 使用酶

时间:2018-05-08 00:38:35

标签: javascript reactjs enzyme

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

3 个答案:

答案 0 :(得分:2)

Enzyme的simulate正在您的Todo组件上寻找onChange事件,而且它没有找到。你没有将onChange指定为道具,所以它没有触发它是有意义的。如果这是您要测试的方式,请将onChange道具连接到您的组件。来自文档:

  

即使名称暗示这模拟了一个实际的事件,   .simulate()实际上将基于该目标来定位组件的道具   你给它的事件。例如,.simulate(&#39;点击&#39;)实际上会得到   onClick道具并调用它。

答案 1 :(得分:1)

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

改变这个:

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

对此:

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

答案 2 :(得分:1)

查看您的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')

相关问题