나는 최근을 테스트하고 싶어하는 일부 사용자 지정 메서드를 가져옵니 조건에 따라에서 호출componentDidMount
방식의 반응을 구성 요소입니다.
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
나는'm 를 사용하여 농담으로 나레이트하는,포함하는농담.fn()
에 대한 조롱/스파이입니다. 나는've 읽는 것이 상당히 사소한 테스트와 Sinon,을 수행하여 다음과 같:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
나는'm 을 다시 만들려고 하다가 이와 같은 농담도록:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
이 코드가 실패하고 발생 다음과 같은 오류가:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
그것은 가능한 이를 테스트하는 기능과 함께 농담으? 고 할 수 있다면,어떻게 해야 하나요?
키를 사용하여 jestsspyOn
방법입니다. 그것은 다음과 같이해야한다:
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
으로 여기 예를 들면:https://stackoverflow.com/questions/40393486/test-if-function-is-called-react-and-enzyme
***참고하시기 바랍그것은 또한 최상의 방법을 취소 감시 기능을 각 시험 후 실행*
let spy
afterEach(() => {
spy.mockClear()
})
https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks
내가 알고있는 조금 늦었어,하지만 이와는 것이 좋을 테스트하는componentDidMount
호출을 시작을 중첩하는 방법 당신의 테스트는 다음과 같아야 합니다:
모듈
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
스 테스트-Good
it('should call methodName during componentDidMount', () => {
const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
const wrapper = mount(<MyComponent {...props} />);
expect(methodNameFake).toHaveBeenCalledTimes(1);
});
에 전화하면componentDidMount
다음에는 주장은호출
이라고를 통해componentDidMount
더 유효합니다.
스 테스트-나쁜
it('should call methodName during componentDidMount', () => {
const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();
}
를 작성하여 이 테스트는 다음과 같이-메서드를 호출한 다음 주장하는 그것에 부름을 받았습니다. 는 것입니다 물론 당신에게만 불렀습니다.