[英]Testing handle change function in React using Enzyme and Jest
My react component contains this code 我的react组件包含此代码
handleChange = e => {
this.setState({
num: e.target.value
});
};
render() {
return (
<div>
<h2>Delete cat :(</h2>
<input
onChange={this.handleChange}
type="number"
placeholder="enter id here"
/>
<button id="deleteBtn" onClick={this.deleteOne}>
Delete
</button>
</div>
);
}
}
As you can see, the handleChange function fires when the input changes and will update state from there. 如您所见,handleChange函数会在输入更改时触发,并从那里更新状态。
How can I test this using Enzyme? 如何使用酶进行测试? I've tried
我试过了
it("Updates the state", () => {
const wrapper = shallow(
<Provider store={store}>
<DeleteOne />
</Provider>
);
const input = wrapper.find("input");
input.simulate("change", { target: { num: 2} });
expect(wrapper.state().num).toEqual(2);
});
});
I had to attempt to wrap it in store because I'm using Redux and exporting a connected component. 我不得不尝试将其包装在商店中,因为我正在使用Redux并导出连接的组件。 I've been Googling the last hour and trying all sorts but weren't able to get this test passing.
我过去一个小时一直在Google上搜索,尝试了各种尝试,但未能通过此测试。 Please send help :) cheers
请发送帮助:)欢呼
PS: I've tested the button click no worries as it just runs a function (no state update). PS:我已经测试了按钮单击无后顾之忧,因为它只运行一个功能(无状态更新)。
I typically export both the connected component for use in the app, and the component itself for testing. 我通常会同时导出要在应用程序中使用的已连接组件和该组件本身以进行测试。
Looks like you've got a small typo, pass { target: { value: 2 } }
as your event. 看来您有一个小错字,将
{ target: { value: 2 } }
作为您的事件。
Here is a working example based on the code you provided: 这是一个基于您提供的代码的工作示例:
import * as React from 'react';
import { shallow } from 'enzyme';
class DeleteOne extends React.Component {
handleChange = e => {
this.setState({
num: e.target.value
});
};
render() {
return (
<div>
<h2>Delete cat :(</h2>
<input
onChange={this.handleChange}
type="number"
placeholder="enter id here"
/>
<button id="deleteBtn" onClick={this.deleteOne}>
Delete
</button>
</div>
);
}
}
it("Updates the state", () => {
const wrapper = shallow(<DeleteOne />);
const input = wrapper.find("input");
input.simulate("change", { target: { value: 2 } }); // 'value' instead of 'num'
expect(wrapper.state().num).toEqual(2); // SUCCESS
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.