프로그래밍 언어/NODE JS

유닛 테스트(3)

· 코딩마이데이

jest에서는 모듈도 모킹할 수 있습ㅂ니다. jest.mock 메서드를 사용합니다.

jest.mock("../models/user");
const User = require("../models/user");
const { addFollowing } = require("./user");

describe("addFollowing", () => {
  const req = {
    user: { id: 1 },
    params: { id: 2 },
  };
  const res = {
    status: jest.fn(() => res),
    send: jest.fn(),
  };
  const next = jest.fn();

  test("사용자를 찾아 팔로잉을 추가하고 success를 응답해야 함", async () => {
    User.findOne.mockReturnValue(
      Promise.resolve({
        addFollowing(id) {
          return Promise.resolve(true);
        },
      })
    );
    await addFollowing(req, res, next);
    expect(res.send).toBeCalledWith("success");
  });

  test("사용자를 못 찾으면 next(error)를 호출함", async () => {
    const error = "사용자 못 찾음";
    User.findOne.mockReturnValue(Promise.reject(error));
    await addFollowing(req, res, next);
    expect(next).toBeCalledWith(error);
  });
});

 

jest.mock 메서드에 모킹할 모듈의 경로를 인수로 넣고, 그 모듈을 불러옵니다. jest.mock에서 모킹할 메서드(User.findOne)에 mockReturnValue라는 메서드를 넣습니다. 이 메서드로 가짜 반환값이 지정할 수 있습니다.

첫 번째 테스트에서는 mockReturnValue 메서드를 통해 User.findOne이 { addFollowing() } 객체를 반환하도록 했습니다. 사용자를 찾아서 팔로잉을 추가하는 상황을 테스트하기 위해서입니다. 프로미스를 반환해야 다음에 await user.addFollowing 메서드를 호출할 수 있습니다. 두 번째 테스트에서는 null을 반환하여 사용자를 찾지 못한 상황을 테스트합니다. 세 번쨰 테스트에서 Promise.reject로 에러가 발생하도록 했습니다. DB 역할에 에러가 발생한 상황을 모킹한 것입니다.

 

이제 테스트를 통과합니다.

$ npm test

> nodebird@0.0.1 test
> jest

(node:4724) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
(node:8284) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 PASS  routes/middlewares.test.js
 PASS  controllers/user.test.js
  ● Console

    console.error controllers/user.js:13
      테스트용 에러


Test Suites: 2 passed, 2 total
Tests:       7 passed, 7 total
Snapshots:   0 total
Time:        8.007s
Ran all test suites.
PS D:\공부\Nodejs\nod

 

실제 데이터베이스에 팔로잉을 등록하는 것이 아니므로 제대로 테스트되는 것인지 걱정할 수 도 있습니다. 이처럼 테스트를 해도 실제 서비스의 실제 데이터베이스에서는 문제가 발생할 수 있습니다. 그럴 때는 유닛 테스트 말고 다른 종류의 테스트를 진행해야 합니다. 이를 점검하기 위해 통합 테스트나 시스템 테스트를 하곤 합니다.

 

'프로그래밍 언어 > NODE JS' 카테고리의 다른 글

웹 소캣 이해하기  (0) 2026.01.08
테스트 커버리지  (0) 2025.12.26
유닛 테스트(2)  (0) 2025.12.20
유닛 테스트  (0) 2025.12.16
노드 서비스 테스트하기 - 테스트 준비하기  (0) 2025.12.13