Recientemente quería probar que algún método personalizado es llamado condicionalmente en el método componentDidMount
de un componente React.
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
Estoy usando Jest como mi framework de pruebas, que incluye jest.fn()
para mocks/spies. He leído que esto sería bastante trivial de probar con Sinon, haciendo algo como lo siguiente:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
Estoy tratando de recrear esto con Jest así:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
Este código falla y arroja el siguiente error:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
¿Es posible probar esta funcionalidad con Jest? Y si es así, ¿cómo?
La clave es usar el método spyOn
de jests. Debería ser así:
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
Como aquí, por ejemplo: https://stackoverflow.com/questions/40393486/test-if-function-is-called-react-and-enzyme
Tenga en cuenta también es una buena práctica borrar la función espiada después de cada prueba.
let spy
afterEach(() => {
spy.mockClear()
})
https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks
Sé que es un poco tarde, pero me encontré con esto y me gustaría sugerir que para probar componentDidMount
inicia la llamada a su método anidado que su prueba debe ser algo como:
Modulo
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
Prueba - Bien
it('should call methodName during componentDidMount', () => {
const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
const wrapper = mount(<MyComponent {...props} />);
expect(methodNameFake).toHaveBeenCalledTimes(1);
});
Si llamas a componentDidMount
entonces la afirmación de que methodName
fue llamado a través de componentDidMount
es más válida.
Prueba - Mal
it('should call methodName during componentDidMount', () => {
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
}
Escribiendo el test así - llamas al método y luego afirmas que fue llamado. Que por supuesto lo habrá hecho dado que acabas de llamarlo.