Vai al contenuto principale
{ "message": "Versione: Prossima", "description": "" }

Un esempio asincrono

Traduzione Beta Non Ufficiale

Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →

Per prima cosa, abilita il supporto Babel in Jest come documentato nella guida Per iniziare.

Implementiamo un modulo che recupera i dati utente da un'API e restituisce il nome dell'utente.

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

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

Nell'implementazione precedente, ci aspettiamo che il modulo request.js restituisca una promise. Concateniamo una chiamata a then per ricevere il nome utente.

Ora immagina un'implementazione di request.js che accede alla rete e recupera alcuni dati utente:

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.
// This module is being mocked in __mocks__/request.js
http.get({path: url}, response => {
let data = '';
response.on('data', _data => (data += _data));
response.on('end', () => resolve(data));
});
});
}

Poiché non vogliamo accedere alla rete nei nostri test, creeremo un mock manuale per il nostro modulo request.js nella cartella __mocks__ (il nome della cartella è case-sensitive, __MOCKS__ non funzionerà). Potrebbe essere simile a questo:

__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.`,
}),
);
});
}

Ora scriviamo un test per la nostra funzionalità asincrona.

__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'));
});

Chiamiamo jest.mock('../request') per dire a Jest di usare il nostro mock manuale. it si aspetta che il valore restituito sia una Promise che verrà risolta. Puoi concatenare tutte le Promise che vuoi e chiamare expect in qualsiasi momento, purché restituisca una Promise alla fine.

.resolves

Esiste un metodo meno verboso utilizzando resolves per estrarre il valore di una promise soddisfatta insieme a qualsiasi altro matcher. Se la promise viene rifiutata, l'asserzione fallirà.

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

async/await

È possibile scrivere test utilizzando la sintassi async/await. Ecco come scriveresti gli stessi esempi precedenti:

// async/await can be used.
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');
});

Per abilitare async/await nel tuo progetto, installa @babel/preset-env e abilita la funzionalità nel tuo file babel.config.js.

Gestione degli errori

Gli errori possono essere gestiti usando il metodo .catch. Assicurati di aggiungere expect.assertions per verificare che venga chiamato un certo numero di asserzioni. Altrimenti una promise soddisfatta non farebbe fallire il test:

// Testing for async errors using 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

L'helper .rejects funziona come .resolves. Se la promise viene soddisfatta, il test fallirà automaticamente. expect.assertions(number) non è obbligatorio ma è consigliato per verificare che venga chiamato un certo numero di asserzioni durante un test. Altrimenti è facile dimenticare di fare return/await sulle asserzioni .resolves.

// Testing for async errors using `.rejects`.
it('tests error with rejects', () => {
expect.assertions(1);
return expect(user.getUserName(3)).rejects.toEqual({
error: 'User with 3 not found.',
});
});

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

Il codice per questo esempio è disponibile su examples/async.

Se vuoi testare timer come setTimeout, consulta la documentazione Timer mocks.