Estoy cambiando a Jest de Mocha, y me pregunto si hay una forma de espiar un método React. Por ejemplo, digamos que tengo el siguiente método en mi componente (ignore la biblioteca sdk , solo construye una llamada jQuery Ajax):
getData() { sdk.getJSON('/someURL').done(data => { this.setState({data}); }); }Usando Sinon probaría esto espiando el prototipo así:
it('should call getData', () => { sinon.spy(Component.prototype, 'getData'); mount(<Component />); expect(Component.prototype.getData.calledOnce).to.be.true; });Esto aseguraría la cobertura del código sin burlarse del método. ¿Existe una funcionalidad similar en Jest?
EDITAR: Además, si esta funcionalidad no existe, ¿cuál es la siguiente mejor estrategia para probar las llamadas a la API?
En realidad puedes usar jest.spyOn jest.spyOn
Si se llama al método cuando se crea el componente, use:
import { mount } from 'enzyme'; describe('My component', () => { it('should call getData', () => { const spy = jest.spyOn(Component.prototype, 'getData'); mount(<Component />); expect(spy).toHaveBeenCalledTimes(1) }); })o si lo tiene en su DOM y usa el método bind , puede usar:
import { shallow } from 'enzyme'; describe('My component', () => { it('should call getData', () => { const wrapper = shallow(<Component />); const instance = wrapper.instance() const spy = jest.spyOn(instance, 'getData'); wrapper.find('button').simulate('click') expect(spy).toHaveBeenCalledTimes(1) }); })Puede optar por el nuevo método spyOn o el siguiente también debería funcionar bien.
it('should call getData', () => { Component.prototype.getData = jest.fn(Component.prototype.getData); expect(Component.prototype.getData).toBeCalled(); });