예를 들어, peanut butter
라는 문자를 반환하는 fetchData
함수가 있다고 가정해보자.
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
}):
async
와 await
을 사용 할 수 있다.async
를 사용하기 위해서는 test에 넘기는 함수 앞에 async
키워드를 추가 해야 한다.test('this data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut buttuer');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
try{
await fetchData();
} catch(e){
expect(e).toMatch('error');
}
});
async
와 await
을 .resolves
또는 .rejects
와 함께 사용할수 있다.test('this data is peanut buttuer', async () => {
await expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', async ()=>{
await expect(fetchData()).rejects.toMatch('error')
});
promise
가 rejected 될 것을 예상한다면, .catch
메소드를 사용할 수 있다. 대신 expect.assertions
으로 명확한 수의 assertions가 호출 되는지를 make sure 해줘야 한다. 그렇지 않으면, fullfilled promise는 테스트에 실패한다.test('the fetch fails with an error', ()=>{
expect.assertions(1);
return fetchData().catch(e => expect(e).toMatch('error'));
});
fetchData
가 promise를 리턴하는게 아니라, 데이터를 가지고 오고 callback(null, data)
를 호출한다고 가정해보자. // 올바르지 않은 예
test('the data is peanut butter', ()=>{
function callback(error,data){
if (error) {
throw error;
}
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
fetchData
가 끝나면서 테스트가 종료 된다는 것이다. done
을 넣어보자. Jest는 test가 끝나기전에 done
callback이 호출될때까지 기다릴 것이다.done()
이 호출되지 않는다면, 테스트는 실패할것이다(with timeout error)expect
구문이 실패한다면, 에러를 던질것이고 done()
은 호출되 지 않을것이다. 만약 왜 실패했는지 test log를 보고싶다면, try
block 안에서 expect
를 감싸야 하고 catch
block 안의 done
에게 에러를 전달해야 한다. 그렇지 않으면 timeout error 를 마주칠 것이다. done()
은 Promises와 섞이면 테스트의 메모리 유출이 발생하므로 함게 사용하면 안된다.test('the data is peanut butter', done=>{
function callback(error,data){
if(error){
done(error);
return;
}
try{
expect(data).toBe('peanut butter');
done();
} catch (error) {
done(error);
}
}
fetchData(callback);
});
expect
문에 .resolves
를 사용할 수 있다. test('the data is peanut butter', ()=>{
return expect(fetchData()).resolves.toBe('peanut butter');
});
test('the data is peanut butter', ()=>{
return expect(fetchData()).rejects.toMatch('error');
});
reference : https://jestjs.io/docs/asynchronous