programing

Jest를 사용하여 메서드 호출을 감시하려면 어떻게 해야 합니까?

megabox 2023. 2. 23. 22:41
반응형

Jest를 사용하여 메서드 호출을 감시하려면 어떻게 해야 합니까?

최근에 어떤 커스텀 메서드가 조건부로 호출되는 것을 테스트하고 싶었습니다.componentDidMountReact 컴포넌트의 메서드.

componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}

Jest를 테스트 프레임워크로 사용하고 있습니다.이거는 다음을 포함합니다.jest.fn()모크/모크용.Sinon을 사용하여 테스트하는 것은 다음과 같은 간단한 작업이라고 합니다.

sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();

Jest와 함께 이렇게 재현하려고 합니다.

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]

Jest를 사용하여 이 기능을 테스트할 수 있습니까?그렇다면 어떻게?

열쇠는 농담을 사용하는 것이다.spyOn오브젝트상의 메서드prototype. 다음과 같이 해야 합니다.

const spy = jest.spyOn(Component.prototype, 'methodName');
const wrapper = mount(<Component {...props} />);
wrapper.instance().methodName();
expect(spy).toHaveBeenCalled();

여기서 볼 수 있는 예:기능을 반응 및 효소라고 하는지 테스트

부디 참고하세요 또한 각 테스트 실행 후 스파이 기능을 삭제하는 것이 좋습니다.

let spy

afterEach(() => {
  spy.mockClear()
})

https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks

좀 늦은 건 알지만 우연히 이런 걸 알게 돼서componentDidMount는, 네스트 된 메서드에의 콜을 개시합니다.이 메서드는 다음과 같습니다.

모듈

componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}

테스트 - 양호

it('should call methodName during componentDidMount', () => {
    const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName');
    const wrapper = mount(<MyComponent {...props} />);
    expect(methodNameFake).toHaveBeenCalledTimes(1);
});

전화하시면componentDidMount라고 하는 주장methodName를 통해 호출되었다.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();
}

이렇게 시험을 작성하면 메서드를 호출하고 호출했다고 단언할 수 있습니다.물론 그렇게 불렀을 수도 있죠

테스트하는 경우public호출되는 메서드componentDidMount(TypeScript를 사용하는 경우) 명시적으로instancecomponentDidMount메서드 호출. 퍼블릭 메서드는 컴포넌트가 인스턴스화될 때까지 정의되지 않기 때문입니다.

다음과 같은 테스트를 수행하려면:

코드

public componentDidMount() {
  if (this.props.initOpen) {
    this.methodName();
  }
}

public methodName = () => {
  // some code here
}

시험

it('should call methodName during componentDidMount', () => {
  const wrapper = mount(<MyComponent {...props} />);
  const instance = wrapper.instance();
  jest.spyOn(instance, 'methodName')
  expect(instance.methodName).toHaveBeenCalled();
});
const toastMethodSpy = jest.spyOn(sharedMockedOTPComponent, 'toast')
sharedMockedOTPComponent.handleResendOtpFailure(networkError)

//hide loader
expect(sharedMockedOTPComponent.state.showLoader).toBe(false)
//error message in toast should have been shown
expect(toastMethodSpy).toHaveBeenCalledTimes(1)

언급URL : https://stackoverflow.com/questions/43245040/how-can-i-use-jest-to-spy-on-a-method-call

반응형