bytrustu tech blog

[Jest] 비동기 테스트 하기 본문

TDD

[Jest] 비동기 테스트 하기

bytrustu 2022. 12. 19. 01:10
비동기 함수를 테스트해보자.

 

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