javascript - 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 } ]
解决方案
Enzyme's正在您的 Todo 组件上simulate
寻找一个onChange
事件,但它没有找到。您没有onChange
指定为道具,因此它没有触发是有道理的。onChange
如果这是您想要测试它的方式,请将 prop 连接到您的组件。从文档:
尽管名称暗示这模拟了一个实际事件,但 .simulate() 实际上会根据你给它的事件来定位组件的 prop。例如, .simulate('click') 实际上会获取 onClick 属性并调用它。
推荐阅读
- javascript - 如何同时收听单击和双击右键
- c++ - 初始化 Pair 的向量
带有 emplace_back - python - 模拟股市收益的随机数
- ios - iPhone Cordova 应用程序不断闪烁白色
- bookdown - 单个页面上没有引用...?
- reactjs - 加载资源:上传 React/Node/Express 后的 net::ERR_CONNECTION_REFUSED
- python - ValueError:传递值的形状为 (12, 8),索引暗示 (12, 12) 和 .describe()
- python - 使用 python 运行指令时出错
- html - div 的 vw 宽度集,但由于某种原因,它们不对齐
- flutter - Android Studio 中的 Flutter 和 Dark SDK 路径没有改变