Jest에서 error를 발생시켜야 하는 경우 테스트
이제 기능 작동이 끝나고 온갖 에러 상황에서 제대로 작동하는지를 테스트 하기 위해 일부러 틀린 내용을 넣어서 jest를 테스트 하는 단계이다.
Expect · Jest
When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.
jestjs.io
위의 jest 공식 문서에서 어떤 문법을 써야 하는지 살펴보기로 하였다.
https://jestjs.io/docs/expect#tothrowerror
Expect · Jest
When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.
jestjs.io
현재 만든 모듈은 조건에 만족하지 않을 시 에러를 리턴해주어야 한다. 따라서 .toThrow(error?)를 사용하기로 하였다.
test('throws on octopus', () => {
expect(() => {
drinkFlavor('octopus');
}).toThrow();
});
위와 같은 상황에서
function drinkFlavor(flavor) {
if (flavor == 'octopus') {
throw new DisgustingFlavorError('yuck, octopus flavor');
}
// Do some other stuff
}
drinkFlaver가 리턴하는 에러가 다음과 같다면, 에러가 발생하고, 테스트는 통과하게 된다.
test('throws on octopus', () => {
function drinkOctopus() {
drinkFlavor('octopus');
}
// Test that the error message says "yuck" somewhere: these are equivalent
expect(drinkOctopus).toThrowError(/yuck/);
expect(drinkOctopus).toThrowError('yuck');
// Test the exact error message
expect(drinkOctopus).toThrowError(/^yuck, octopus flavor$/);
expect(drinkOctopus).toThrowError(new Error('yuck, octopus flavor'));
// Test that we get a DisgustingFlavorError
expect(drinkOctopus).toThrowError(DisgustingFlavorError);
});
위와 같이 특정 에러가 나는지 체크할 수도 있다.
expect(new 클래스명(들어가는api값)).toThrowError(에러타입 또는 메세지);
이렇게 잘못된 클래스 생성시에 에러를 리턴해주는 모듈이므로, 위와 같이 에러를 써주면 된다.