테스트 코드에서 toThrow를 통과하지 못하는 에러가 발생했다. 코드 내용은 아래와 같다.
[auth.service.ts]
createToken(address: string): Token {
if (address === undefined) {
throw new Error('address should be defined.');
}
return {
expiresIn: 3600,
accessToken: this.jwtService.sign(address),
};
}
[auth.service.spec.ts]
it('should throw "address should be defined"', async () => {
service = new AuthService(instance(mockJwtService),
instance(mockUserService),
instance(mockValidationService));
expect(service.createToken(undefined)).toThrow('address should be defined.');
});
expect에서 자꾸 걸려 테스트를 통과하지 못했다.
에러 메시지를 보니, auth.service의 throw new error가 실행되면서 테스트 코드가 실패하고 있다.
it('should throw "address should be defined"', async () => {
service = new AuthService(instance(mockJwtService),
instance(mockUserService),
instance(mockValidationService));
// async 하지 않을 때는 내부에서 throw를 처리할 때 이렇게 해야 한다.
expect(() => {
service.createToken(undefined);
}).toThrow('address should be defined.');
});
해결 방법은 위와 같다. auth.service의 createToken()은 Promise가 아니다. 해당 메소드가 Promise가 아닐 때는 throw 처리법이 조금 다르다. Promise라면 점(.)을 따라 순차적으로 처리를 해준다.
예를 들어, expect(service.createToken(undefined)).toThrow('address should be defined.'); 를 살펴보면 service -> createToken -> toThrow 순으로 처리해준다.
Promise가 아닐 경우엔 throw가 발생하는 createToken에서 처리해줘야 하므로 () => 를 추가하면 이 문제를 해결할 수 있다.
'개발새발 개발자 > JavaScript' 카테고리의 다른 글
[NestJS] DI 처리 후 Module에 등록하기 (0) | 2019.07.01 |
---|---|
[NestJs] Authentication 도전기 - 2 (feat.초보에겐 너무나 어려운 공식 문서) (0) | 2019.05.19 |
[NestJs] Authentication 도전기 - 1 (feat.초보에겐 너무나 어려운 공식 문서) (2) | 2019.05.17 |
[javascript] 스토리지 및 DOM 조작법 (0) | 2018.12.07 |
[Vue.js] router 정보 보기 (0) | 2018.12.07 |