Skip to main content
Versão: 29.6

Um Exemplo de Async

Primeiro, ative o suporte para Babel em Jest conforme documentado no guia de Introdução.

Vamos implementar um módulo simples que busca dados de usuário de uma API e retorna o nome de usuário.

user.js
import request from './request';

export function getUserName(userID) {
return request(`/users/${userID}`).then(user => user.name);
}

In the above implementation, we expect the request.js module to return a promise. We chain a call to then to receive the user name.

Now imagine an implementation of request.js that goes to the network and fetches some user data:

request.js
const http = require('http');

export default function request(url) {
return new Promise(resolve => {
// This is an example of an http request, for example to fetch
// user data from an API.
// Este modulo está sendo simulado em __mocks__/request.js
http.get({path: url}, response => {
let data = '';
response.on('data', _data => (data += _data));
response.on('end', () => resolve(data));
});
});
}

Because we don't want to go to the network in our test, we are going to create a manual mock for our request.js module in the __mocks__ folder (the folder is case-sensitive, __MOCKS__ will not work). Pode ficar parecido com:

__mocks__/request.js
const users = {
4: {name: 'Mark'},
5: {name: 'Paul'},
};

export default function request(url) {
return new Promise((resolve, reject) => {
const userID = parseInt(url.slice('/users/'.length), 10);
process.nextTick(() =>
users[userID]
? resolve(users[userID])
: reject({
error: `User with ${userID} not found.`,
}),
);
});
}

Agora vamos escrever um teste para a nossa funcionalidade async.

__tests__/user-test.js
jest.mock('../request');

import * as user from '../user';

// The assertion for a promise must be returned.
it('works with promises', () => {
expect.assertions(1);
return user.getUserName(4).then(data => expect(data).toBe('Mark'));
});

Nós chamamos jest.mock('../request') para informar Jest para usar nossa simulação manual. it espera que o valor de retorno seja uma promessa que vai ser resolvida. You can chain as many Promises as you like and call expect at any time, as long as you return a Promise at the end.

.resolves

Existe uma maneira menos verbosa usando resolves para decodificar o valor de uma promessa cumprida, juntamente com quaisquer outro matcher. Se a promessa for rejeitada, a afirmação falhará.

it('works with resolves', () => {
expect.assertions(1);
return expect(user.getUserName(5)).resolves.toBe('Paul');
});

async/await

Writing tests using the async/await syntax is also possible. Here is how you'd write the same examples from before:

// async/await pode ser usado.
it('works with async/await', async () => {
expect.assertions(1);
const data = await user.getUserName(4);
expect(data).toBe('Mark');
});

// async/await can also be used with `.resolves`.
it('works with async/await and resolves', async () => {
expect.assertions(1);
await expect(user.getUserName(5)).resolves.toBe('Paul');
});

To enable async/await in your project, install @babel/preset-env and enable the feature in your babel.config.js file.

Tratamento de erros

Erros podem ser tratados usando 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 falharia no teste:

// Testando para erros async usando Promise.catch.
it('tests error with promises', () => {
expect.assertions(1);
return user.getUserName(2).catch(error =>
expect(error).toEqual({
error: 'User with 2 not found.',
}),
);
});

// Or using async/await.
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await user.getUserName(1);
} catch (error) {
expect(error).toEqual({
error: 'User with 1 not found.',
});
}
});

.rejects

The.rejects helper works like the .resolves helper. Se a promessa é cumprida, o teste automaticamente irá falhar. expect.assertions(number) is not required but recommended to verify that a certain number of assertions are called during a test. It is otherwise easy to forget to return/await the .resolves assertions.

// Testando para erros async usando `.rejects`.
it('testa erro com rejects', () => {
expect.assertions(1);
return expect(user.getUserName(3)).rejects.toEqual({
error: 'User with 3 not found.',
});
});


// Ou usando async/await com `.rejects`.
it('testa erro com async/await e rejects', async () => {
expect.assertions(1);
await expect(user.getUserName(3)).rejects.toEqual({
error: 'User with 3 not found.',
});
});

The code for this example is available at examples/async.

If you'd like to test timers, like setTimeout, take a look at the Timer mocks documentation.