2017-02-24 2 views
5

나는 모카에서 농담으로 바꾼다. 나는 반작용 방법을 간첩 할 방법이 있는지 궁금하다. 예를 들어 내가 내 구성 요소에서 다음과 같은 방법을 말할 수의 경우 (SDK를 라이브러리 무시, 그냥 JQuery와 아약스 호출을 구성) : sinon를 사용Jest spy on functionality

getData() { 
    sdk.getJSON('/someURL').done(data => { 
     this.setState({data}); 
    }); 
} 

내가 이렇게 같은 프로토 타입을 감시하여이를 테스트하는 것입니다 :

it('should call getData',() => { 
     sinon.spy(Component.prototype, 'getData'); 
     mount(<Component />); 
     expect(Component.prototype.getData.calledOnce).to.be.true; 
    }); 

이렇게하면 방법을 조롱하지 않고 코드 커버리지를 보장 할 수 있습니다. 농담에 비슷한 기능이 있습니까?

편집 : 또한이 기능이없는 경우 API 호출을 테스트하기위한 차세대 전략은 무엇입니까?

답변

6

당신은 당신이 새로운 spyOn 방법에 갈 수

3

을 찾고하거나 다음해야 또한 잘 작동 정확히 않는, 그 일부 일 전 V19에 도입되었으며, spyOn 방법이있다. 메서드를 호출 할 경우

it('should call getData',() => { 
    Component.prototype.getData = jest.fn(Component.prototype.getData); 
    expect(Component.prototype.getData).toBeCalled(); 
}); 
+0

그게 전부는 아닙니다. 'syon.spy'와 마찬가지로'getData'를 덮어 쓰는 반면'sinon.spy'와'jest.spyOn'는 원래 메소드를 호출합니다. –

+0

맞아! 대답을 수정했습니다. –

1

사실 당신은 jest.spyOn jest.spyOn

를 사용할 수있을 때 구성 요소를 만들어 사용 :

import { mount } from 'enzyme'; 

describe('My component',() => { 
    it('should call getData',() => { 
    const spy = jest.spyOn(Component.prototype, 'getData'); 
    mount(<Component />); 
    expect(Component.prototype.getData).toHaveBeenCalledTimes(1) 
    }); 
}) 

또는 당신은 당신의 DOM 및 방법 사용 바인드 그것을있는 경우 다음을 사용할 수 있습니다 :

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) 
    }); 
})