Estoy probando un componente react con Mocha y Enzyme. Aquí está el componente (acortado para simplificar, por supuesto):
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>
)
}
}
Y aquí está la prueba:
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);
})
Espero que cuando el usuario escriba texto en la caja <input>
se llame al método handleChange
. La prueba anterior falla con:
AssertionError: expected false to equal true
+ expected - actual
-false
+true
at Context.<anonymous> (test/components/new_component_test.js:71:45)
¿Qué estoy haciendo mal?
Debo aclarar, mi objetivo es probar que el método handleChange
es llamado. ¿Cómo puedo hacerlo?
Usted puede simplemente espiar al método directamente a través del prototipo.
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);
})
Alternativamente, puedes usar spy en el método de la instancia, pero tienes que hacer una actualización forzada porque el componente ya está renderizado después de que mount sea llamado, lo que significa que el onChange ya está ligado a su 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);
})