tes*_*est 6 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);
});
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,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 } ]
Run Code Online (Sandbox Code Playgroud)
Enzymesimulate
正在寻找onChange
您的 Todo 组件上的事件,但它没有找到。你没有onChange
指定为道具,所以它没有触发是有道理的。onChange
如果这是您要测试的方式,请将道具连接到您的组件。从文档:
尽管名称暗示这是模拟实际事件,但 .simulate() 实际上将根据您提供的事件定位组件的 prop。例如, .simulate('click') 实际上会获取 onClick 道具并调用它。
您正在尝试模拟单击具有 class 的元素addtocart
。但是,您没有带有 class 的元素addtocart
。您的添加按钮的元素 ID 为submit
。
改变这个:
const submitButton = wrapper.find('.addtocart');
对此:
const submitButton = wrapper.find('#submit');
归档时间: |
|
查看次数: |
5482 次 |
最近记录: |