The enzyme mimics the onChange event

I am testing a reactive 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 expect that when the user types the text in the <input> field, the handleChange method will be called. Test Failure Above:

 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?

EDIT

I have to clarify, my goal is to check if the handleChange method is handleChange . How can i do this?

+8
javascript reactjs mocha enzyme
source share
1 answer

You can just look into the method directly through 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 for the instance method, but you must force the update because the component is already visible after calling mount, which means that onChange is already bound to its original.

 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); }) 
+10
source share

All Articles