Promises
- 테스트 함수가 프로미스 값을 사용하는 경우, 따로 처리를 하지 않는 경우 데이터는 resolve 되야하고 reject 발생시 fail 처리됨
- 프로미스로 reject값을 받아오고 싶은경우 catch문으로 처리
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
test('the fetch fails with an error', () => {
expect.assertions(1);
return fetchData().catch(e => expect(e).toMatch('error'));
});
Async/Await
test('the data is peanut butter', async () => {
const data = await fetchData();
expect(data).toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
expect.assertions(1);
try {
await fetchData();
} catch (e) {
expect(e).toMatch('error');
}
});
test('the data is peanut butter', async () => {
await expect(fetchData()).resolves.toBe('peanut butter');
});
test('the fetch fails with an error', async () => {
await expect(fetchData()).rejects.toMatch('error');
});
Callbacks
- Jest는 함수의 마지막줄까지 함수를 읽으면 테스트를 종료함
test('the data is peanut butter', () => {
function callback(error, data) {
if (error) {
throw error;
}
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
- 콜백함수를 테스트하기 위해서는 done을 사용해야 함
- 테스트에서 done() 콜백이 호출되면 테스트가 종료되고, 만약 호출되지 않으면 timeout error를 발생시킴
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);
});