Expect
Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →
Durante la scrittura dei test, spesso è necessario verificare che i valori soddisfino determinate condizioni. expect fornisce accesso a una serie di "matcher" che ti permettono di convalidare diversi aspetti.
Per ulteriori matcher Jest mantenuti dalla community, consulta jest-extended.
Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →
Gli esempi TypeScript in questa pagina funzioneranno come documentato solo se importi esplicitamente le API di Jest:
import {expect, jest, test} from '@jest/globals';
Consulta la guida Per iniziare per i dettagli su come configurare Jest con TypeScript.
Riferimento
- La funzione expect
- Modificatori
- Matcher
.toBe(value).toHaveBeenCalled().toHaveBeenCalledTimes(number).toHaveBeenCalledWith(arg1, arg2, ...).toHaveBeenLastCalledWith(arg1, arg2, ...).toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....).toHaveReturned().toHaveReturnedTimes(number).toHaveReturnedWith(value).toHaveLastReturnedWith(value).toHaveNthReturnedWith(nthCall, value).toHaveLength(number).toHaveProperty(keyPath, value?).toBeCloseTo(number, numDigits?).toBeDefined().toBeFalsy().toBeGreaterThan(number | bigint).toBeGreaterThanOrEqual(number | bigint).toBeLessThan(number | bigint).toBeLessThanOrEqual(number | bigint).toBeInstanceOf(Class).toBeNull().toBeTruthy().toBeUndefined().toBeNaN().toContain(item).toContainEqual(item).toEqual(value).toMatch(regexp | string).toMatchObject(object).toMatchSnapshot(propertyMatchers?, hint?).toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot).toStrictEqual(value).toThrow(error?).toThrowErrorMatchingSnapshot(hint?).toThrowErrorMatchingInlineSnapshot(inlineSnapshot)
- Matcher Asimmetrici
expect.anything()expect.any(constructor)expect.arrayContaining(array)expect.not.arrayContaining(array)expect.arrayOf(value)expect.not.arrayOf(value)expect.closeTo(number, numDigits?)expect.objectContaining(object)expect.not.objectContaining(object)expect.stringContaining(string)expect.not.stringContaining(string)expect.stringMatching(string | regexp)expect.not.stringMatching(string | regexp)
- Conteggio delle asserzioni
- Utilità di estensione
- Proprietà serializzabili
La funzione expect
expect(value)
La funzione expect viene utilizzata ogni volta che vuoi testare un valore. Raramente chiamerai expect da sola. Piuttosto, userai expect insieme a una funzione "matcher" per verificare qualcosa riguardo a un valore.
È più facile capire con un esempio. Supponi di avere un metodo bestLaCroixFlavor() che dovrebbe restituire la stringa 'grapefruit'. Ecco come lo testeresti:
test('the best flavor is grapefruit', () => {
expect(bestLaCroixFlavor()).toBe('grapefruit');
});
In questo caso, toBe è la funzione matcher. Esistono molte funzioni matcher diverse, documentate di seguito, per aiutarti a testare vari aspetti.
L'argomento di expect dovrebbe essere il valore prodotto dal tuo codice, mentre l'argomento del matcher dovrebbe essere il valore corretto. Se li inverti, i test funzioneranno comunque, ma i messaggi di errore appariranno confusi.
Modificatori
.not
Se sai come testare qualcosa, .not ti permette di testare il suo opposto. Ad esempio, questo codice verifica che il miglior gusto La Croix non sia cocco:
test('the best flavor is not coconut', () => {
expect(bestLaCroixFlavor()).not.toBe('coconut');
});
.resolves
Usa resolves per estrarre il valore di una promise risolta, così puoi concatenare altri matcher. Se la promise viene rifiutata, l'asserzione fallisce.
Ad esempio, questo codice verifica che la promise venga risolta e che il valore risultante sia 'lemon':
test('resolves to lemon', () => {
// make sure to add a return statement
return expect(Promise.resolve('lemon')).resolves.toBe('lemon');
});
Poiché stai ancora testando promise, il test rimane asincrono. Dovrai quindi dire a Jest di attendere restituendo l'asserzione estratta.
In alternativa, puoi usare async/await in combinazione con .resolves:
test('resolves to lemon', async () => {
await expect(Promise.resolve('lemon')).resolves.toBe('lemon');
await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus');
});
.rejects
Usa .rejects per estrarre il motivo di una promise rifiutata, così puoi concatenare altri matcher. Se la promise viene risolta, l'asserzione fallisce.
Ad esempio, questo codice verifica che la promise venga rifiutata con il motivo 'octopus':
test('rejects to octopus', () => {
// make sure to add a return statement
return expect(Promise.reject(new Error('octopus'))).rejects.toThrow(
'octopus',
);
});
Poiché stai ancora testando promise, il test rimane asincrono. Dovrai quindi dire a Jest di attendere restituendo l'asserzione estratta.
In alternativa, puoi usare async/await in combinazione con .rejects.
test('rejects to octopus', async () => {
await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus');
});
Matcher
.toBe(value)
Usa .toBe per confrontare valori primitivi o verificare l'identità referenziale di istanze di oggetti. Utilizza Object.is per confrontare i valori, che è persino migliore per i test dell'operatore di uguaglianza stretta ===.
Ad esempio, questo codice convalida alcune proprietà dell'oggetto can:
const can = {
name: 'pamplemousse',
ounces: 12,
};
describe('the can', () => {
test('has 12 ounces', () => {
expect(can.ounces).toBe(12);
});
test('has a sophisticated name', () => {
expect(can.name).toBe('pamplemousse');
});
});
Non usare .toBe con numeri a virgola mobile. Ad esempio, a causa dell'arrotondamento in JavaScript, 0.2 + 0.1 non è strettamente uguale a 0.3. Per i numeri a virgola mobile, usa invece .toBeCloseTo.
Anche se il matcher .toBe verifica l'identità referenziale, segnala un confronto approfondito dei valori se l'asserzione fallisce. Se le differenze tra le proprietà non ti aiutano a capire perché un test fallisce, specialmente se il report è lungo, puoi spostare il confronto direttamente nella funzione expect. Ad esempio, per verificare se gli elementi sono la stessa istanza:
-
riscrivi
expect(received).toBe(expected)comeexpect(Object.is(received, expected)).toBe(true) -
riscrivi
expect(received).not.toBe(expected)comeexpect(Object.is(received, expected)).toBe(false)
.toHaveBeenCalled()
Usa .toHaveBeenCalled per verificare che una funzione mock sia stata chiamata.
Ad esempio, supponi di avere una funzione drinkAll(drink, flavour) che applica una funzione drink a tutte le bevande disponibili. Potresti voler verificare che drink venga effettivamente chiamata. Puoi farlo con questo test:
function drinkAll(callback, flavour) {
if (flavour !== 'octopus') {
callback(flavour);
}
}
describe('drinkAll', () => {
test('drinks something lemon-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'lemon');
expect(drink).toHaveBeenCalled();
});
test('does not drink something octopus-flavoured', () => {
const drink = jest.fn();
drinkAll(drink, 'octopus');
expect(drink).not.toHaveBeenCalled();
});
});
.toHaveBeenCalledTimes(number)
Usa .toHaveBeenCalledTimes per verificare che una funzione mock sia stata chiamata un numero preciso di volte.
Ad esempio, supponi di avere una funzione drinkEach(drink, Array<flavor>) che applica una funzione drink a un array di bevande. Potresti voler verificare che la funzione drink sia stata chiamata esattamente il numero corretto di volte. Puoi farlo con questo test:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).toHaveBeenCalledTimes(2);
});
.toHaveBeenCalledWith(arg1, arg2, ...)
Usa .toHaveBeenCalledWith per verificare che una funzione mock sia stata chiamata con argomenti specifici. Gli argomenti vengono confrontati con lo stesso algoritmo usato da .toEqual.
Ad esempio, supponi di poter registrare una bevanda con una funzione register, e che applyToAll(f) debba applicare la funzione f a tutte le bevande registrate. Per verificare che funzioni, potresti scrivere:
test('registration applies correctly to orange La Croix', () => {
const beverage = new LaCroix('orange');
register(beverage);
const f = jest.fn();
applyToAll(f);
expect(f).toHaveBeenCalledWith(beverage);
});
.toHaveBeenLastCalledWith(arg1, arg2, ...)
Se hai una funzione mock, puoi usare .toHaveBeenLastCalledWith per verificare con quali argomenti è stata chiamata per ultima. Ad esempio, supponi di avere una funzione applyToAllFlavors(f) che applica f a diversi gusti, e vuoi assicurarti che quando viene chiamata, l'ultimo gusto elaborato sia 'mango'. Puoi scrivere:
test('applying to all flavors does mango last', () => {
const drink = jest.fn();
applyToAllFlavors(drink);
expect(drink).toHaveBeenLastCalledWith('mango');
});
.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)
Se hai una funzione mock, puoi usare .toHaveBeenNthCalledWith per verificare con quali argomenti è stata chiamata all'n-esima chiamata. Ad esempio, supponi di avere una funzione drinkEach(drink, Array<flavor>) che applica f a diversi gusti, e vuoi assicurarti che quando viene chiamata, il primo gusto elaborato sia 'lemon' e il secondo 'octopus'. Puoi scrivere:
test('drinkEach drinks each drink', () => {
const drink = jest.fn();
drinkEach(drink, ['lemon', 'octopus']);
expect(drink).toHaveBeenNthCalledWith(1, 'lemon');
expect(drink).toHaveBeenNthCalledWith(2, 'octopus');
});
L'argomento n deve essere un numero intero positivo a partire da 1.
.toHaveReturned()
Se hai una funzione mock, puoi usare .toHaveReturned per verificare che la funzione mock sia tornata con successo (cioè senza lanciare errori) almeno una volta. Ad esempio, supponi di avere un mock drink che restituisce true. Puoi scrivere:
test('drinks returns', () => {
const drink = jest.fn(() => true);
drink();
expect(drink).toHaveReturned();
});
.toHaveReturnedTimes(number)
Usa .toHaveReturnedTimes per verificare che una funzione mock sia tornata con successo (senza lanciare errori) un numero preciso di volte. Le chiamate che generano errori non vengono conteggiate.
Ad esempio, supponi di avere un mock drink che restituisce true. Puoi scrivere:
test('drink returns twice', () => {
const drink = jest.fn(() => true);
drink();
drink();
expect(drink).toHaveReturnedTimes(2);
});
.toHaveReturnedWith(value)
Usa .toHaveReturnedWith per verificare che una funzione mock abbia restituito un valore specifico.
Ad esempio, supponi di avere una funzione mock drink che restituisce il nome della bevanda consumata. Puoi scrivere:
test('drink returns La Croix', () => {
const beverage = {name: 'La Croix'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage);
expect(drink).toHaveReturnedWith('La Croix');
});
.toHaveLastReturnedWith(value)
Usa .toHaveLastReturnedWith per verificare il valore specifico restituito dall'ultima chiamata a una funzione mock. Se l'ultima chiamata ha generato un errore, questo matcher fallirà indipendentemente dal valore fornito come risultato atteso.
Ad esempio, supponi di avere una funzione mock drink che restituisce il nome della bevanda consumata. Puoi scrivere:
test('drink returns La Croix (Orange) last', () => {
const beverage1 = {name: 'La Croix (Lemon)'};
const beverage2 = {name: 'La Croix (Orange)'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage1);
drink(beverage2);
expect(drink).toHaveLastReturnedWith('La Croix (Orange)');
});
.toHaveNthReturnedWith(nthCall, value)
Usa .toHaveNthReturnedWith per verificare il valore specifico restituito da una funzione mock nella chiamata numero n. Se l'n-esima chiamata ha generato un errore, questo matcher fallirà indipendentemente dal valore fornito come risultato atteso.
Ad esempio, supponi di avere una funzione mock drink che restituisce il nome della bevanda consumata. Puoi scrivere:
test('drink returns expected nth calls', () => {
const beverage1 = {name: 'La Croix (Lemon)'};
const beverage2 = {name: 'La Croix (Orange)'};
const drink = jest.fn(beverage => beverage.name);
drink(beverage1);
drink(beverage2);
expect(drink).toHaveNthReturnedWith(1, 'La Croix (Lemon)');
expect(drink).toHaveNthReturnedWith(2, 'La Croix (Orange)');
});
L'argomento n deve essere un numero intero positivo a partire da 1.
.toHaveLength(number)
Usa .toHaveLength per verificare che un oggetto abbia una proprietà .length con un valore numerico specifico.
Particolarmente utile per controllare la dimensione di array o stringhe.
expect([1, 2, 3]).toHaveLength(3);
expect('abc').toHaveLength(3);
expect('').not.toHaveLength(5);
.toHaveProperty(keyPath, value?)
Usa .toHaveProperty per verificare l'esistenza di una proprietà nel percorso keyPath di un oggetto. Per proprietà annidate, utilizza la dot notation o un array contenente il percorso completo.
Puoi fornire un argomento opzionale value per confrontare il valore della proprietà (con uguaglianza profonda come il matcher toEqual).
L'esempio seguente mostra un oggetto houseForSale con proprietà annidate. Usiamo toHaveProperty per verificare esistenza e valori di diverse proprietà.
// Object containing house features to be tested
const houseForSale = {
bath: true,
bedrooms: 4,
kitchen: {
amenities: ['oven', 'stove', 'washer'],
area: 20,
wallColor: 'white',
'nice.oven': true,
},
livingroom: {
amenities: [
{
couch: [
['large', {dimensions: [20, 20]}],
['small', {dimensions: [10, 10]}],
],
},
],
},
'ceiling.height': 2,
};
test('this house has my desired features', () => {
// Example Referencing
expect(houseForSale).toHaveProperty('bath');
expect(houseForSale).toHaveProperty('bedrooms', 4);
expect(houseForSale).not.toHaveProperty('pool');
// Deep referencing using dot notation
expect(houseForSale).toHaveProperty('kitchen.area', 20);
expect(houseForSale).toHaveProperty('kitchen.amenities', [
'oven',
'stove',
'washer',
]);
expect(houseForSale).not.toHaveProperty('kitchen.open');
// Deep referencing using an array containing the keyPath
expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20);
expect(houseForSale).toHaveProperty(
['kitchen', 'amenities'],
['oven', 'stove', 'washer'],
);
expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven');
expect(houseForSale).toHaveProperty(
'livingroom.amenities[0].couch[0][1].dimensions[0]',
20,
);
expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']);
expect(houseForSale).not.toHaveProperty(['kitchen', 'open']);
// Referencing keys with dot in the key itself
expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall');
});
.toBeCloseTo(number, numDigits?)
Usa toBeCloseTo per confrontare numeri in virgola mobile con uguaglianza approssimata.
L'argomento opzionale numDigits limita il numero di cifre decimali da verificare. Con il valore predefinito 2, il criterio è Math.abs(expected - received) < 0.005 (cioè 10 ** -2 / 2).
I confronti diretti spesso falliscono per errori di arrotondamento nella rappresentazione binaria. Ad esempio, questo test fallisce:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBe(0.3); // Fails!
});
Fallisce perché in JavaScript 0.2 + 0.1 restituisce effettivamente 0.30000000000000004.
Esempio con precisione a 5 cifre decimali:
test('adding works sanely with decimals', () => {
expect(0.2 + 0.1).toBeCloseTo(0.3, 5);
});
Poiché toBeCloseTo risolve specificamente errori da virgola mobile, non supporta valori interi molto grandi.
.toBeDefined()
Usa .toBeDefined per verificare che una variabile non sia undefined. Ad esempio, per controllare che una funzione fetchNewFlavorIdea() restituisca qualcosa:
test('there is a new flavor idea', () => {
expect(fetchNewFlavorIdea()).toBeDefined();
});
Potresti scrivere expect(fetchNewFlavorIdea()).not.toBe(undefined), ma è buona pratica evitare di riferirsi direttamente a undefined.
.toBeFalsy()
Usa .toBeFalsy quando vuoi verificare che un valore sia falso in un contesto booleano, indipendentemente dal suo tipo. Ad esempio, supponi questo codice:
drinkSomeLaCroix();
if (!getErrors()) {
drinkMoreLaCroix();
}
Potresti non interessarti di cosa restituisce getErrors nello specifico - potrebbe essere false, null o 0, e il tuo codice funzionerebbe comunque. Quindi, se vuoi verificare che non ci siano errori dopo aver bevuto una La Croix, potresti scrivere:
test('drinking La Croix does not lead to errors', () => {
drinkSomeLaCroix();
expect(getErrors()).toBeFalsy();
});
In JavaScript esistono sei valori falsy: false, 0, '', null, undefined e NaN. Tutto il resto è considerato truthy.
.toBeGreaterThan(number | bigint)
Usa toBeGreaterThan per verificare received > expected con valori numerici o big integer. Ad esempio, per testare che ouncesPerCan() restituisca un valore maggiore di 10 once:
test('ounces per can is more than 10', () => {
expect(ouncesPerCan()).toBeGreaterThan(10);
});
.toBeGreaterThanOrEqual(number | bigint)
Usa toBeGreaterThanOrEqual per verificare received >= expected con valori numerici o big integer. Ad esempio, per testare che ouncesPerCan() restituisca almeno 12 once:
test('ounces per can is at least 12', () => {
expect(ouncesPerCan()).toBeGreaterThanOrEqual(12);
});
.toBeLessThan(number | bigint)
Usa toBeLessThan per verificare received < expected con valori numerici o big integer. Ad esempio, per testare che ouncesPerCan() restituisca meno di 20 once:
test('ounces per can is less than 20', () => {
expect(ouncesPerCan()).toBeLessThan(20);
});
.toBeLessThanOrEqual(number | bigint)
Usa toBeLessThanOrEqual per verificare received <= expected con valori numerici o big integer. Ad esempio, per testare che ouncesPerCan() restituisca al massimo 12 once:
test('ounces per can is at most 12', () => {
expect(ouncesPerCan()).toBeLessThanOrEqual(12);
});
.toBeInstanceOf(Class)
Usa .toBeInstanceOf(Class) per verificare che un oggetto sia istanza di una classe. Questo matcher utilizza internamente instanceof.
class A {}
expect(new A()).toBeInstanceOf(A);
expect(() => {}).toBeInstanceOf(Function);
expect(new A()).toBeInstanceOf(Function); // throws
.toBeNull()
.toBeNull() è equivalente a .toBe(null) ma produce messaggi d'errore più chiari. Usa .toBeNull() quando vuoi verificare esplicitamente un valore null.
function bloop() {
return null;
}
test('bloop returns null', () => {
expect(bloop()).toBeNull();
});
.toBeTruthy()
Usa .toBeTruthy quando non ti interessa il valore specifico ma vuoi assicurarti che sia truthy in un contesto booleano. Ad esempio, supponi di avere del codice come:
drinkSomeLaCroix();
if (thirstInfo()) {
drinkMoreLaCroix();
}
Potresti non interessarti di cosa restituisce thirstInfo - potrebbe essere true o un oggetto complesso - purché il codice funzioni. Per verificare che thirstInfo sia truthy dopo aver bevuto una La Croix:
test('drinking La Croix leads to having thirst info', () => {
drinkSomeLaCroix();
expect(thirstInfo()).toBeTruthy();
});
In JavaScript esistono sei valori falsy: false, 0, '', null, undefined e NaN. Tutto il resto è considerato truthy.
.toBeUndefined()
Usa .toBeUndefined per verificare che una variabile sia undefined. Ad esempio, per testare che bestDrinkForFlavor(flavor) restituisca undefined per il gusto 'octopus' (non esistendo bevande al gusto di polpo):
test('the best drink for octopus flavor is undefined', () => {
expect(bestDrinkForFlavor('octopus')).toBeUndefined();
});
Potresti usare expect(bestDrinkForFlavor('octopus')).toBe(undefined), ma è buona pratica evitare riferimenti diretti a undefined.
.toBeNaN()
Usa .toBeNaN per verificare che un valore sia NaN.
test('passes when value is NaN', () => {
expect(NaN).toBeNaN();
expect(1).not.toBeNaN();
});
.toContain(item)
Usa .toContain quando vuoi verificare che un elemento sia presente in un array. Per testare gli elementi nell'array, questo utilizza ===, un controllo di uguaglianza stretta. .toContain può anche verificare se una stringa è una sottostringa di un'altra stringa.
Ad esempio, se getAllFlavors() restituisce un array di gusti e vuoi assicurarti che contenga lime:
test('the flavor list contains lime', () => {
expect(getAllFlavors()).toContain('lime');
});
Questo matcher supporta anche altri iterabili come stringhe, set, node list e HTML collections.