Testing Asynchronous Code
É comum em JavaScript executar código de forma assíncrona. Quando você tiver o código que é executado de forma assíncrona, Jest precisa saber quando o código que está testando for concluído, antes que possa passar para outro teste. Jest tem várias maneiras de lidar com isso.
Callbacks
O padrão assíncrono mais comum são as "callbacks".
Por exemplo, digamos que você tem uma função fetchData(callback)
que busca alguns dados e chama callback(data)
quando está completa. Você deseja testar que este dado retornado seja apenas a string 'peanut butter'
.
By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:
// Don't do this!
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
O problema é que o teste será concluído logo que fetchData
completa, antes de sequer chamar a "callback".
Há uma forma alternativa de test
que corrige isto. Em vez de colocar o teste em uma função com um argumento vazio, use um único argumento chamado done
. Jest aguardará até que a "callback" done
é chamada antes de terminar o teste.
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
Se done()
nunca é chamada, o teste falhará, que é o que você quer que aconteça.
Promises
Se seu código usa "promises", ou promessas, há uma maneira mais simples para lidar com testes assíncronos. Jest retorna uma promessa de seu teste, e Jest irá aguardar a promessa ser resolvida. Se a promessa for rejeitada, o teste automaticamente irá falhar.
For example, let's say that fetchData
, instead of using a callback, returns a promise that is supposed to resolve to the string 'peanut butter'
. We could test it with:
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});
Be sure to return the promise - if you omit this return
statement, your test will complete before the promise returned from fetchData
resolves and then() has a chance to execute the callback.
Se você espera que uma promessa seja rejeitada, use o método catch
. Se certifique de adicionar expect.assertions
para verificar que um certo número de afirmações são chamadas. Caso contrário, uma promessa cumprida não iria falhar no teste.
test('the fetch fails with an error', () => {
expect.assertions(1);
return fetchData().catch(e => expect(e).toMatch('error'));
});
.resolves
/ .rejects
You can also use the .resolves
matcher in your expect statement, and Jest will wait for that promise to resolve. Se a promessa for rejeitada, o teste automaticamente irá falhar.
test('the data is peanut butter', () => {
return expect(fetchData()).resolves.toBe('peanut butter');
});
Be sure to return the assertion—if you omit this return
statement, your test will complete before the promise returned from fetchData
is resolved and then() has a chance to execute the callback.
Se você espera que uma promessa seja rejeitada, use o "matcher" .rejects
. Ele funciona analogicamente para o "matcher" .resolves
. Se a promessa é cumprida, o teste automaticamente irá falhar.
test('the fetch fails with an error', () => {
return expect(fetchData()).rejects.toMatch('error');
});
Async/Await
Como alternativa, você pode usar async
e await
em seus testes. Para escrever um teste async, basta usar a palavra-chave async
na frente da função passada para test
. Por exemplo, o mesmo cenário de fetchData
pode ser testado com:
test('the data is peanut butter', async () => {
expect.assertions(1);
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');
}
});
Of course, you can combine async
and await
with .resolves
or .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.toThrow('error');
});
Nestes casos, async
e await
são efetivamente apenas uma sintaxe mais simples da mesma lógica dos exemplos de uso de promessas.
None of these forms is particularly superior to the others, and you can mix and match them across a codebase or even in a single file. It just depends on which style makes your tests simpler.