Object
jest.spyOn(object, methodName)
jest.spyOn은 jest.fn와 유사하게 모의 함수를 생성하지만,
object[methodName]에 대한 호출을 추적한다.
jest 모의 함수를 반환한다.
함수 덮어쓰기
jest.spyOn은 스파이한 메서드를 호출한다. 원래 함수를 덮어쓰고 싶다면,
jest.spyOn(object, methodName).mockImplementation(()=> customImplementation) 또는 object[methodName] = jest.fn(()=> customImplementation) 을 사용하면 된다.
const video = {
play() {
return true;
},
};
export default video;import video from "./video";
afterEach(() => {
jest.restoreAllMocks();
});
test("plays video with mock implementation using jest.spyOn", () => {
const spy = jest.spyOn(video, "play").mockImplementation(() => false);
const isPlaying = video.play();
expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(false);
});using 키워드와 함께
TypeScript >= 5.2 또는 @babel/plugin-proposal-explicit-resource-management 플러그인을 사용하는 경우, using 키워드와 함께 spyOn을 사용할 수 있다
이 코드는 다음과 같다.
getter 와 setter
jest 22.1.0 부터 jest.spyOn 메서드는 선택적인 세 번째 인수 accessType을 받을 수 있으며, 이는 get 또는 set이 될 수 있다.
Last updated