[英]Enzyme simulate an onChange event
I'm testing a react component with Mocha and Enzyme. 我正在用摩卡和酶测试反应成分。 Here is the component (shortened for simplicity of course): 这是组件(当然简化为简化):
class New extends React.Component {
// shortened for simplicity
handleChange(event) {
// handle changing state of input
const target = event.target;
const value = target.value;
const name = target.name
this.setState({[name]: value})
}
render() {
return(
<div>
<form onSubmit={this.handleSubmit}>
<div className="form-group row">
<label className="col-2 col-form-label form-text">Poll Name</label>
<div className="col-10">
<input
className="form-control"
ref="pollName"
name="pollName"
type="text"
value={this.state.pollName}
onChange={this.handleChange}
/>
</div>
</div>
<input className="btn btn-info" type="submit" value="Submit" />
</form>
</div>
)
}
}
And here is the test: 以下是测试:
it("responds to name change", done => {
const handleChangeSpy = sinon.spy();
const event = {target: {name: "pollName", value: "spam"}};
const wrap = mount(
<New handleChange={handleChangeSpy} />
);
wrap.ref('pollName').simulate('change', event);
expect(handleChangeSpy.calledOnce).to.equal(true);
})
I am expecting that when the user types text into the <input>
box the handleChange
method will be called. 我希望当用户在<input>
框中键入文本时,将调用handleChange
方法。 The test above fails with: 以上测试失败:
AssertionError: expected false to equal true
+ expected - actual
-false
+true
at Context.<anonymous> (test/components/new_component_test.js:71:45)
What am I doing wrong? 我究竟做错了什么?
I should clarify, my objective is to test that the method handleChange
is called. 我应该澄清一下,我的目标是测试方法handleChange
是否被调用。 How can I do that? 我怎样才能做到这一点?
You can simply spy to the method directly via the prototype. 您可以通过原型直接窥探方法。
it("responds to name change", done => {
const handleChangeSpy = sinon.spy(New.prototype, "handleChange");
const event = {target: {name: "pollName", value: "spam"}};
const wrap = mount(
<New />
);
wrap.ref('pollName').simulate('change', event);
expect(handleChangeSpy.calledOnce).to.equal(true);
})
Alternatively, you can use spy on the instance's method, but you have to make a forced update because the component is already rendered after mount is called, which means the onChange is already bound to its original. 或者,您可以在实例的方法上使用spy,但是您必须进行强制更新,因为在调用mount之后该组件已经呈现,这意味着onChange已经绑定到其原始。
it("responds to name change", done => {
const event = {target: {name: "pollName", value: "spam"}};
const wrap = mount(
<New />
);
const handleChangeSpy = sinon.spy(wrap.instance(), "handleChange");
wrap.update(); // Force re-render
wrap.ref('pollName').simulate('change', event);
expect(handleChangeSpy.calledOnce).to.equal(true);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.