🗃️ 내가 다시 볼 것

[Jest] bcrypt.compare mocking

전호영 2024. 2. 21. 12:55
  async authenticateUser(user: LoginUserDto) {
    const existingUser = await this.usersRepository.findUserByEmail(user.email);
    if (!existingUser) {
      throw new UnauthorizedException('Email이 존재하지 않습니다.');
    }

    const isMatch = await bcrypt.compare(user.password, existingUser.password);
    if (!isMatch) {
      throw new UnauthorizedException('비밀번호가 일치하지 않습니다.');
    }
    return existingUser;
  }

 

위 코드의 테스트 코드를 작성하던 중 bcrypt를 만났다.

bcrypt.compare는 다음과 같이 mocking할 수 있다. 

// 에러
const bcryptCompare = jest.fn().mockRejectedValue(new Error('Random error'));
(bcrypt.compare as jest.Mock) = bcryptCompare;

// 통과
const bcryptCompare = jest.fn().mockResolvedValue(true);
(bcrypt.compare as jest.Mock) = bcryptCompare;

 

위 예시를 나의 테스트 코드에 적용시켜보자.

describe.only('bcrypt mocking example', () => {
    it('should return UnauthorizedException _ pw not matched', async () => {
      const user = new LoginUserDto();
      user.email = 'test@test.com';
      user.password = '1234';
      const existingUser = new User();
      existingUser.email = user.email;
      existingUser.password = '123';
      jest.spyOn(repository, 'findUserByEmail').mockResolvedValue(false);
      const bcryptCompare = jest.fn().mockResolvedValue(false);
      (bcrypt.compare as jest.Mock) = bcryptCompare;
      await expect(async () => service.authenticateUser(user)).rejects.toThrow(
        new UnauthorizedException('비밀번호가 일치하지 않습니다.'),
      );
    });
  });

  it('should return User', async () => {
    const user = new LoginUserDto();
    user.email = 'test@test.com';
    user.password = '1234';
    const existingUser = new User();
    existingUser.email = user.email;
    existingUser.password = '1234';
    const bcryptCompare = jest.fn().mockResolvedValue(true);
    (bcrypt.compare as jest.Mock) = bcryptCompare;
    jest.spyOn(repository, 'findUserByEmail').mockResolvedValue(existingUser);

    const result = await service.authenticateUser(user);
    expect(result).toEqual(existingUser);
  });

 

 

정상적으로 mocking이 된 것을 알 수 있다.

 


참고

https://gist.github.com/jpmoura/720171a4e5ded4bd8bc6ba69271d0b34