8
我正在測試與摩卡和酶的反應組件。下面是組件(縮短課程的簡單):酶模擬onChange事件
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>
)
}
}
,這裏是測試:
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);
})
我期待的是,當用戶鍵入文本到<input>
框中handleChange
法會調用。上述測試失敗:
AssertionError: expected false to equal true
+ expected - actual
-false
+true
at Context.<anonymous> (test/components/new_component_test.js:71:45)
我在做什麼錯?
編輯
我要澄清,我的目標是測試方法handleChange
被調用。我怎樣才能做到這一點?
您可以直接使用'sinon.spy(object,「method」)來窺探對象的方法' –