테스트 환경 설정

  • index.js

    const resultHandler = require("./resultHandler");
    
    const init = (bool) => {
      if (bool) {
        resultHandler("success");
      }
      resultHandler("fail");
    };
    
    module.exports = init;
    
  • resultHandler.js

    const resultHandler = (str) => str;
    module.exports = resultHandler;
    

이 상황에서 init의 인자에 따라 resultHandler가 적절한 인자로 호출이 되는지 확인해보자.

const init = require("../index");
const resultHandler = require("../resultHandler");

jest.mock("../resultHandler");

test("true로 호출 시 success로 호출된다.", () => {
  init(true);
  expect(resultHandler).toBeCalledWith("success");
});

test("false로 호출 시 fail로 호출된다.", () => {
  init(false);
  expect(resultHandler).toBeCalledWith("fail");
});

위 코드처럼, 모듈을 mock 함수로 생성하고 어떤 인자로 호출되었는지 확인할 수 있다.

인자 뿐만 아니라, 호출된 횟수, 호출 여부, n번째 호출 인자, 마지막 호출 인자 등을 테스트할 수도 있다.

또한 특정 mock 함수가 리턴할 값을 명시해줄 수 있다. (모듈을 임의로 구현할 수 있다.)

예를 들어 bool값을 특정 함수로 받아오도록 수정해보자.

const resultHandler = require("./resultHandler");
const giveMeBoolean = require("./giveMeBoolean");

const init = () => {
  const bool = giveMeBoolean();
  if (bool) {
    resultHandler("success");
  }
  resultHandler("fail");
};
init();
module.exports = init;

여기서 giveMeBoolean은 단순히 true를 리턴하는 함수이지만 true, false중 리턴값이 예측되지 않는 함수라고 생각해보자.

const init = require("../index");
const resultHandler = require("../resultHandler");
const giveMeBoolean = require("../giveMeBoolean");

jest.mock("../giveMeBoolean", () => {
  return () => true;
});

jest.mock("../resultHandler");

test("true로 호출 시 success로 호출된다.", () => {
  init();
  expect(resultHandler).toBeCalledWith("success");
});

jest.mock의 callback을 이용해 giveMeBoolean을 mock함수로 생성함과 동시에 true를 반환하도록 구현할 수 있다.