Utilizzo dei Matcher
Questa pagina è stata tradotta da PageTurner AI (beta). Non ufficialmente approvata dal progetto. Hai trovato un errore? Segnala problema →
Jest utilizza i "matcher" per testare valori in modi diversi. Questo documento introdurrà alcuni matcher comunemente usati. Per l'elenco completo, consulta la documentazione dell'API expect.
Matcher Comuni
Il modo più semplice per testare un valore è tramite uguaglianza esatta.
test('two plus two is four', () => {
expect(2 + 2).toBe(4);
});
In questo codice, expect(2 + 2) restituisce un oggetto "expectation". Tipicamente non interagirai molto con questi oggetti se non per chiamare matcher su di essi. Qui, .toBe(4) è il matcher. Quando Jest viene eseguito, tiene traccia di tutti i matcher falliti per mostrarti messaggi d'errore chiari.
toBe utilizza Object.is per verificare l'uguaglianza esatta. Per controllare il valore di un oggetto, usa toEqual:
test('object assignment', () => {
const data = {one: 1};
data['two'] = 2;
expect(data).toEqual({one: 1, two: 2});
});
toEqual verifica ricorsivamente ogni campo di un oggetto o array.
toEqual ignora chiavi d'oggetto con proprietà undefined, elementi di array undefined, sparsità di array o mismatch di tipi d'oggetto. Per considerare questi aspetti usa invece toStrictEqual.
Puoi anche testare l'opposto di un matcher usando not:
test('adding positive numbers is not zero', () => {
for (let a = 1; a < 10; a++) {
for (let b = 1; b < 10; b++) {
expect(a + b).not.toBe(0);
}
}
});
Veridicità
Nei test, a volte devi distinguere tra undefined, null e false, ma altre volte preferisci non trattarli diversamente. Jest offre helper per specificare esattamente ciò che desideri.
-
toBeNullcorrisponde solo anull -
toBeUndefinedcorrisponde solo aundefined -
toBeDefinedè l'opposto ditoBeUndefined -
toBeTruthycorrisponde a qualsiasi valore che un'istruzioneifconsidera vero -
toBeFalsycorrisponde a qualsiasi valore che un'istruzioneifconsidera falso
Per esempio:
test('null', () => {
const n = null;
expect(n).toBeNull();
expect(n).toBeDefined();
expect(n).not.toBeUndefined();
expect(n).not.toBeTruthy();
expect(n).toBeFalsy();
});
test('zero', () => {
const z = 0;
expect(z).not.toBeNull();
expect(z).toBeDefined();
expect(z).not.toBeUndefined();
expect(z).not.toBeTruthy();
expect(z).toBeFalsy();
});
Scegli il matcher che corrisponde più precisamente al comportamento desiderato del tuo codice.
Numeri
La maggior parte dei confronti numerici ha equivalenti matcher.
test('two plus two', () => {
const value = 2 + 2;
expect(value).toBeGreaterThan(3);
expect(value).toBeGreaterThanOrEqual(3.5);
expect(value).toBeLessThan(5);
expect(value).toBeLessThanOrEqual(4.5);
// toBe and toEqual are equivalent for numbers
expect(value).toBe(4);
expect(value).toEqual(4);
});
Per l'uguaglianza in virgola mobile, usa toBeCloseTo invece di toEqual, per evitare che i test dipendano da piccoli errori di arrotondamento.
test('adding floating point numbers', () => {
const value = 0.1 + 0.2;
//expect(value).toBe(0.3); This won't work because of rounding error
expect(value).toBeCloseTo(0.3); // This works.
});
Stringhe
Puoi verificare stringhe con espressioni regolari tramite toMatch:
test('there is no I in team', () => {
expect('team').not.toMatch(/I/);
});
test('but there is a "stop" in Christoph', () => {
expect('Christoph').toMatch(/stop/);
});
Array e iterabili
Puoi verificare se un array o iterabile contiene un elemento specifico con toContain:
const shoppingList = [
'diapers',
'kleenex',
'trash bags',
'paper towels',
'milk',
];
test('the shopping list has milk on it', () => {
expect(shoppingList).toContain('milk');
expect(new Set(shoppingList)).toContain('milk');
});
Eccezioni
Per testare se una funzione specifica genera un errore quando chiamata, usa toThrow.
function compileAndroidCode() {
throw new Error('you are using the wrong JDK!');
}
test('compiling android goes as expected', () => {
expect(() => compileAndroidCode()).toThrow();
expect(() => compileAndroidCode()).toThrow(Error);
// You can also use a string that must be contained in the error message or a regexp
expect(() => compileAndroidCode()).toThrow('you are using the wrong JDK');
expect(() => compileAndroidCode()).toThrow(/JDK/);
// Or you can match an exact error message using a regexp like below
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK$/); // Test fails
expect(() => compileAndroidCode()).toThrow(/^you are using the wrong JDK!$/); // Test pass
});
La funzione che genera l'eccezione deve essere invocata all'interno di una funzione wrapper, altrimenti l'asserzione toThrow fallirà.
E altro ancora
Questo è solo un assaggio. Per l'elenco completo dei matcher, consulta la documentazione di riferimento.
Dopo aver appreso i matcher disponibili, il prossimo passo è scoprire come Jest ti permette di testare codice asincrono.