首页 > 解决方案 > React.js - 用 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 } ]

标签: javascriptreactjsenzyme

解决方案


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

尽管名称暗示这模拟了一个实际事件,但 .simulate() 实际上会根据你给它的事件来定位组件的 prop。例如, .simulate('click') 实际上会获取 onClick 属性并调用它。


推荐阅读