Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | 2 | 3 | ||||
| 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 11 | 12 | 13 | 14 | 15 | 16 | 17 |
| 18 | 19 | 20 | 21 | 22 | 23 | 24 |
| 25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- aws s3
- Frontend
- jest
- 모노레포
- github actions
- 데이터 타입
- Jest Matchers
- 마이크로프론트엔드
- 비동기 테스트
- React
- 패캠
- virtual DOM
- Husky
- F-Lab 회고
- F-Lab
- 인프런 멘토링
- ESLint
- 프론트엔드
- 가상돔
- 전역 상태 관리
- F-Lab 오티
- javascript
- Reconsiliation
- 에프랩
- CICD
- 주간 회고
- Prettier
- 패스트캠퍼스
- TDD
- context api
Archives
- Today
- Total
bytrustu tech blog
[Jest] 비동기 테스트 하기 본문
비동기 함수를 테스트해보자.
https://jestjs.io/docs/asynchronous
Testing Asynchronous Code · Jest
It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest has several ways to handle this.
jestjs.io
async.js
fetchProduct 함수의 매개변수가 error의 경우 Error를 발생합니다.
const fetchProduct = (error) => {
if (error === 'error') {
return Promise.reject('네트워크 오류가 발생했습니다.');
}
return Promise.resolve({ id: 1, name: 'bytrustu', price: 1000 });
}
module.exports = fetchProduct;
Promise
test의 callback 함수의 매개변수 첫 번째 값은 완료된 시점을 개발자가 지정할 수 있도록 테스트 가능합니다.
test('Promise 테스트 합니다.', (done) => {
fetchProduct().then((item) => {
expect(item).toEqual(obj);
done();
})
});
비동기 함수의 결과를 return 하게 되면 done 처리가 없더라도 테스트 수행이 가능합니다.
test('비동기 함수의 결과를 return 하여 테스트 합니다.', () => {
return fetchProduct().then((item) => {
expect(item).toEqual(obj);
})
});
Async/Await
test('async await으로 테스트 합니다.', async () => {
const product = await fetchProduct();
expect(product).toEqual(obj);
});
. resolves/. reject
test('resolves 테스트 합니다.', () => {
expect(fetchProduct()).resolves.toEqual(obj);
});
test('resolves 거짓을 테스트 합니다.', () => {
expect(fetchProduct()).resolves.not.toEqual({ ...obj, price: 2000 });
});
test('reject 테스트 합니다.', () => {
expect(fetchProduct('error')).rejects.toBe('네트워크 오류가 발생했습니다.');
});
'TDD' 카테고리의 다른 글
| [Jest] Mock (0) | 2022.12.21 |
|---|---|
| [Jest] Matchers 사용하기 (2) | 2022.12.18 |
| [Jest] 초기 환경설정 (0) | 2022.12.17 |
Comments