본문으로 건너뛰기

[Jest] Unit Test 방법

  author: Dev.ian
createdAt: 2024-08-18
updatedAt: 2024-08-18

Test Target

  • Nest.js Application Code

  • Test Target Method: fetchUser, getUser

    export class UserService {
    async fetchUser(id: string): Promise<User> {
    // check parameter
    if (!id) {
    throw new NoUserException('no exist id');
    }
    // return
    return this.getUSer(id);
    }

    // === private ===
    private async getUser(id: string): Promise<User> {
    const user: User = await db.get(id);
    if (!user) {
    return null;
    }
    return user;
    }
    }

Check Error

  • 에러가 알맞는 Error Object (NoUserException) 인지, 알맞는 Message (no exist id) 인지 체크

toThrowError

  • 비동기처리 Code 를 테스트할 때는 Test 의 결과도 Promise 이다.

    • awaitrejects or resolves 를 이용해 코드를 작성한다.
  • Test code 1

      it('error: no exist id', async () =>{
    // given
    const id = 'test_id';
    const testFunc = async () => {
    await fetchUser(id);
    };
    // when & then
    await expect(() => testFunc()).rejects.toThrowError(new NoUserException('no exist id'));
    }, 999_999_999);
  • Test code 2 (Test code 1 과 동일한 내용)

      it('error: no exist id', async () =>{
    // given
    const id = 'test_id';
    // when & then
    await expect(fetchUser(id)).rejects.toThrowError(new NoUserException('no exist id'));
    }, 999_999_999);

Object 비교

  • 객체Object의 모든 키Key와 값Value이 예상한 값과 동일한지 비교한다.

toStrictEqual

  • Test Code

      it('Object: equal', async () =>{
    // given
    const id = 'test_id';
    // when
    const user = await fetchUser(id);
    // then
    await expect(user).toStrictEqual({id: 'strict-user-id'});
    }, 999_999_999);