
Jest
Testando Código Assíncrono com Jest
É comum em JavaScript executar código de forma assíncrona. Quando você tiver código assíncrono, o Jest precisa saber quando ele foi concluído para então seguir com os testes seguintes. Felizmente, o Jest oferece várias formas de lidar com isso.
• 16 de mai. de 2025
• 4 min de leitura

Promises
Você pode retornar uma Promise no seu teste, e o Jest aguardará até que ela seja resolvida. Se ela for rejeitada, o teste irá falhar.
// fetch.test.js test('the data is peanut butter', () => { return fetchData().then(data => { expect(data).toBe('peanut butter'); }); });
Dica: Certifique-se de retornar a Promise. Se não fizer isso, o Jest pode encerrar o teste antes dela ser resolvida.
Usando async/await
Você também pode usar async/await
, que torna o código mais legível.
test('os dados são manteiga de amendoim', async () => { const data = await fetchData(); expect(data).toBe('peanut butter'); }); `` Tratando erros com `try/catch`: ```js test("O fetch falha com um erro", async () => { expect.assertions(1); try { await fetchData(); } catch (error) { expect(error).toMatch("error"); } });
Com resolves
e rejects
:
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'); });
Atenção
Não se esqueça de usar return
ou await
. Sem isso, o Jest pode considerar o teste finalizado antes da execução dos blocos de expect()
.
Quando você espera erro, use também expect.assertions()
para garantir que as asserções foram chamadas:
test('the fetch fails with an error', () => { expect.assertions(1); return fetchData().catch(error => expect(error).toMatch('error')); });
Callbacks
Se você estiver usando callbacks ao invés de Promises, o Jest também permite lidar com isso usando o argumento done
:
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); });
O Jest lança erro se você combinar done()
com Promises no mesmo teste — evite isso.
.resolves / .rejects
Esses matchers ajudam a deixar o código mais limpo quando trabalhando com Promises.
test('the data is peanut butter', () => { return expect(fetchData()).resolves.toBe('peanut butter'); }); test('the fetch fails with an error', () => { return expect(fetchData()).rejects.toMatch('error'); });
Dica extra
Você pode usar bibliotecas como msw para mockar APIs em testes, tornando os cenários mais realistas.
Tags
Jest
Artigos Relacionados



