Frontend/Jasmine

Difference of spyOn, callThrough, and callFake

ej503 2024. 6. 16. 09:30

메소드를 spy on 할 때, 메소드 호출횟수 등을 기록해보자.

 

class X {
  addNums(x + y) {
    return x + y;
  }
}

const x = new X();
const addNumsSpy = spyOn(x, 'addNums');
const result = x.addNums(1, 2);
expect(addNumsSpy).toHaveBeenCalled();
expect(addNumsSpy).toHaveBeenCalledWith(1, 2);
expect(addNumsSpy).toHaveBeenCalledTimes(1);
console.log(result);

 

result 는 undefined 이며, 3을 예상한 사람도 있을 것이지만 이것은 spy이기 때문에 그렇지 않다. 다시 말해, spyOn은 details 를 지우고 method가 호출되었는지, 어떻게 호출되었는지에 대한 접근 권한을 준다.

 

`callThrough`, `returnValue`, 그리고 `callFake`는 이 undefined된 구현 details 를 활용할 때 필요하다.

 

1. callThrough

 

const x = new X();
const addNumsSpy = spyOn(x, 'addNums').and.callThrough();
const result = x.addNums(1, 2);
expect(addNumsSpy).toHaveBeenCalled();
expect(addNumsSpy).toHaveBeenCalledWith(1, 2);
console.log(result);

 

실제 함수를 호출해 result 는 3이 될것이다. 

 

 

2. returnValue

 

const x = new X();
const addNumsSpy = spyOn(x, 'addNums').and.returnValue(1000);
const result = x.addNum(1, 2);
expect(addNumsSpy).toHaveBeenCalled();
expect(addNumsSpy).toHaveBeenCalledWith(1, 2);
console.log(result);

 

result 는 1000이 될것이다. returnValue 는 구현 details 를 무시하고 즉시 값을 반환한다.

 

 

3. callFake

 

const x = new X();
const addNumsSpy = spyOn(x, 'addNums').and.callFake((num1, num2) => {
  console.log(num1, num2);
  return num1 * num2;
});
const result = x.addNums(1, 2);
expect(addNumsSpy).toHaveBeenCalled();
expect(addNumsSpy).toHaveBeenCalledWith(1, 2);
console.log(result);

 

spy의 구현 details 를 덧셈에서 곱셈으로 변경했기 때문에 result 는 2가 될 것이다.

 

 

original: https://stackoverflow.com/questions/69708498/jasmine-callthrough-and-callfake

'Frontend > Jasmine' 카테고리의 다른 글

Jasmine toBe vs toEqual  (0) 2024.06.27
Creating your calculator and Testing with Jasmine  (2) 2023.03.04
Why unit testing? why jasmine?  (0) 2023.03.01