오늘의 개념 공부 주제는 Jest 이다!
테스트를 간편하게 하기 위한 자바스크립트 테스팅 프레임 워크, 바벨, 타입스크립트, 리액트와 호환이 가능하고 별다른 설정 없이 자바스크립트 프로젝트에서 테스트를 바로 할 수 있다. 큰 객체들을 쉽게 추적해주는 스냅샷 기능이 지원된다. 자체 프로세스에서 테스트가 병렬화되어 실행되어 퍼포먼스를 향상 시킨다. 기초 문법으로는 it-expect 의 통일된 구문의 api 를 사용한다.
npm install --save-dev jest
를 이용해서 설치 후 사용한다.
function sum(a, b) {
return a + b;
}
export default sum;
import sum from './sum';
test('add 1+2 to equal 3', ()=>{
expect(sum(1,2)).toBe(3);
});
이런 식으로 test -> expect 를 작성해서 사용하면 된다.
{
"scripts": {
"test": "jest"
}
}
package.json 속 지정한 명령어를 통해 실행 시키면 console 창에 결과가 출력된다.
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (5ms)
test('----', ()=>{
expect(2+1).toBe(4);
});
test('adding positive numbers is not zero', () => {
for (let a = 1; a < 10; a++) {
for (let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
function compileAndroidCode() {
throw new Error('you are using the wrong JDK!');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
// 에러 메시지도 확인 가능
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/);
});
: 비동기 코드를 테스트 할 때에는 다음 테스트 코드로 넘어가야 되는 지를 알려줘야된다.
Callback 을 사용하는 함수가 있다고 가정하자.
const fetchDataCallback = (cd) => {
setTimeout(()=>{
console.log();
cd("yayy");
}, 3500);
}
흔하게 생각하지만, 잘못된 테스트 방법은
test('the data is yayy', ()=>{
function callback(data){
expect(data).toBe('yayy');
}
fetchDataCallback(callback)
});
이런 경우 올바르게 테스트를 하려면,
test('the data is yayy', done=>{
function callback(data){
try {
expect(data).toBe('yayy');
done();
} catch (error) {
done(error)
}
}
fetchDataCallback(callback)
})
이렇게 test 함수의 인자를 done 으로 받아와서 처리해야하고, 실패 할 수도 있는 경우를 대비해 try, catch 로 예외를 처리한다.