Unit Test 방법
[Jest] Unit Test 방법
섹션 제목: “[Jest] Unit Test 방법” author: Onejay createdAt: 2024-08-18 updatedAt: 2024-08-18Test Target
섹션 제목: “Test Target”-
Nest.js Application Code
-
Test Target Method:
fetchUser,getUserexport class UserService {async fetchUser(id: string): Promise<User> {// check parameterif (!id) {throw new NoUserException('no exist id');}// returnreturn 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
섹션 제목: “Check Error”- 에러가 알맞는 Error Object (NoUserException) 인지, 알맞는 Message (
no exist id) 인지 체크
toThrowError
섹션 제목: “toThrowError”-
비동기처리 Code 를 테스트할 때는 Test 의 결과도 Promise 이다.
await와rejectsorresolves를 이용해 코드를 작성한다.
-
Test code 1
it('error: no exist id', async () =>{// givenconst id = 'test_id';const testFunc = async () => {await fetchUser(id);};// when & thenawait expect(() => testFunc()).rejects.toThrowError(new NoUserException('no exist id'));}, 999_999_999); -
Test code 2 (Test code 1 과 동일한 내용)
it('error: no exist id', async () =>{// givenconst id = 'test_id';// when & thenawait expect(fetchUser(id)).rejects.toThrowError(new NoUserException('no exist id'));}, 999_999_999);
Object 비교
섹션 제목: “Object 비교”- 객체Object의 모든 키Key와 값Value이 예상한 값과 동일한지 비교한다.
toStrictEqual
섹션 제목: “toStrictEqual”-
Test Code
it('Object: equal', async () =>{// givenconst id = 'test_id';// whenconst user = await fetchUser(id);// thenawait expect(user).toStrictEqual({id: 'strict-user-id'});}, 999_999_999);