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

API Globali

Traduzione Beta Non Ufficiale

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

Nei tuoi file di test, Jest inserisce ciascuno di questi metodi e oggetti nell'ambiente globale. Non devi richiedere o importare nulla per utilizzarli. Tuttavia, se preferisci importazioni esplicite, puoi usare import {describe, expect, test} from '@jest/globals'.

Traduzione Beta Non Ufficiale

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

info

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.

Metodi


Riferimento

afterAll(fn, timeout)

Esegue una funzione dopo il completamento di tutti i test in questo file. Se la funzione restituisce una promise o è un generatore, Jest attende che la promise venga risolta prima di proseguire.

Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Utile quando devi ripulire stati globali condivisi tra più test.

Per esempio:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
db.cleanUp();
}

afterAll(() => {
cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

Qui afterAll garantisce che cleanUpDatabase venga chiamato dopo l'esecuzione di tutti i test.

Se afterAll si trova in un blocco describe, viene eseguito alla fine del blocco describe.

Per eseguire operazioni di pulizia dopo ogni singolo test invece che dopo tutti i test, utilizza afterEach.

afterEach(fn, timeout)

Esegue una funzione dopo il completamento di ogni test in questo file. Se la funzione restituisce una promise o è un generatore, Jest attende che la promise venga risolta prima di proseguire.

Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Utile quando devi ripulire stati temporanei creati da ciascun test.

Per esempio:

const globalDatabase = makeGlobalDatabase();

function cleanUpDatabase(db) {
db.cleanUp();
}

afterEach(() => {
cleanUpDatabase(globalDatabase);
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

Qui afterEach garantisce che cleanUpDatabase venga chiamato dopo ogni esecuzione di test.

Se afterEach si trova in un blocco describe, viene eseguito solo dopo i test contenuti in quel blocco describe.

Per eseguire operazioni di pulizia una sola volta dopo tutti i test, utilizza invece afterAll.

beforeAll(fn, timeout)

Esegue una funzione prima dell'avvio di qualsiasi test in questo file. Se la funzione restituisce una promise o è un generatore, Jest attende che la promise venga risolta prima di eseguire i test.

Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Utile per configurare stati globali utilizzati da più test.

Per esempio:

const globalDatabase = makeGlobalDatabase();

beforeAll(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});

// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

Qui beforeAll garantisce la configurazione del database prima dell'esecuzione dei test. Se il setup fosse sincrono, potresti farlo senza beforeAll. L'aspetto chiave è che Jest attende la risoluzione delle promise, consentendo setup asincroni.

Se beforeAll si trova in un blocco describe, viene eseguito all'inizio del blocco describe.

Per eseguire operazioni prima di ogni singolo test invece che prima di tutti i test, utilizza beforeEach.

beforeEach(fn, timeout)

Esegue una funzione prima di ciascun test in questo file. Se la funzione restituisce una promise o è un generatore, Jest attende che la promise venga risolta prima di eseguire il test.

Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Utile per ripristinare stati globali utilizzati da più test.

Per esempio:

const globalDatabase = makeGlobalDatabase();

beforeEach(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});

test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});

test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});

Qui beforeEach garantisce il ripristino del database per ogni test.

Se beforeEach si trova all'interno di un blocco describe, viene eseguito per ogni test nel blocco describe.

Se devi eseguire del codice di configurazione una sola volta, prima di qualsiasi test, utilizza invece beforeAll.

describe(name, fn)

describe(name, fn) crea un blocco che raggruppa più test correlati. Ad esempio, se hai un oggetto myBeverage che dovrebbe essere delizioso ma non aspro, potresti testarlo con:

const myBeverage = {
delicious: true,
sour: false,
};

describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

Non è obbligatorio: puoi scrivere i blocchi test direttamente al livello principale. Ma può essere utile se preferisci organizzare i test in gruppi.

Puoi anche annidare blocchi describe se hai una gerarchia di test:

const binaryStringToNumber = binString => {
if (!/^[01]+$/.test(binString)) {
throw new CustomError('Not a binary number.');
}

return parseInt(binString, 2);
};

describe('binaryStringToNumber', () => {
describe('given an invalid binary string', () => {
test('composed of non-numbers throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrow(CustomError);
});

test('with extra whitespace throws CustomError', () => {
expect(() => binaryStringToNumber(' 100')).toThrow(CustomError);
});
});

describe('given a valid binary string', () => {
test('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
});
});

describe.each(table)(name, fn, timeout)

Utilizza describe.each se ripeti le stesse suite di test con dati diversi. describe.each ti permette di scrivere la suite di test una volta e passare i dati.

describe.each è disponibile con due API:

1. describe.each(table)(name, fn, timeout)

  • table: Array di Array con gli argomenti passati alla fn per ogni riga. Se passi un array monodimensionale di primitive, internamente verrà mappato in una tabella (es. [1, 2, 3] -> [[1], [2], [3]]).

  • name: String il titolo della suite di test.

    • Genera titoli di test univoci iniettando parametri in posizione con la formattazione printf:
      • %p - pretty-format.
      • %s- Stringa.
      • %d- Numero.
      • %i - Intero.
      • %f - Valore in virgola mobile.
      • %j - JSON.
      • %o - Oggetto.
      • %# - Indice del caso di test.
      • %$ - Numero del caso di test.
      • %% - singolo segno di percentuale ('%'). Non consuma argomenti.
    • Oppure genera titoli univoci iniettando proprietà dell'oggetto test case con $variable:
      • Per valori annidati: usa un percorso chiave come $variable.path.to.value (solo per proprietà "proprie", es. $variable.constructor.name non funziona)
      • Usa $# per iniettare l'indice del test case
      • Non combinare $variable con la formattazione printf (tranne per %%)
  • fn: Function la suite di test da eseguire, che riceverà i parametri di ogni riga come argomenti.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

describe.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});

2. describe.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • Prima riga con intestazioni delle colonne separate da |
    • Una o più righe successive con dati forniti come espressioni template literal usando ${value}.
  • name: String il titolo della suite di test, utilizza $variable per iniettare i dati di test nel titolo della suite dalle espressioni template literal taggate, e $# per l'indice della riga.

    • Per iniettare valori di oggetti annidati puoi fornire un keyPath, ad esempio $variable.path.to.value (funziona solo per le "proprietà proprie", ad esempio $variable.constructor.name non funzionerebbe)
  • fn: Function la suite di test da eseguire, questa è la funzione che riceverà l'oggetto con i dati del test.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

describe.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('$a + $b', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});

test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});

test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});

describe.only(name, fn)

Alias equivalente: fdescribe(name, fn)

Puoi usare describe.only per eseguire solo un blocco describe:

describe.only('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

describe('my other beverage', () => {
// ... will be skipped
});

describe.only.each(table)(name, fn)

Alias equivalenti: fdescribe.each(table)(name, fn) e fdescribe.each`table`(name, fn)

Usa describe.only.each per eseguire solo suite di test specifiche basate su dati.

describe.only.each è disponibile con due API:

describe.only.each(table)(name, fn)

describe.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.only.each`table`(name, fn)

describe.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('passes', () => {
expect(a + b).toBe(expected);
});
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.skip(name, fn)

Alias equivalente: xdescribe(name, fn)

Usa describe.skip per non eseguire i test di un blocco describe specifico:

describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});

test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});

describe.skip('my other beverage', () => {
// ... will be skipped
});

Usare describe.skip è spesso più pulito rispetto a commentare temporaneamente blocchi di test. Attenzione: il blocco describe verrà comunque eseguito. Se hai operazioni di setup che devono essere saltate, gestiscile in blocchi beforeAll o beforeEach.

describe.skip.each(table)(name, fn)

Alias equivalenti: xdescribe.each(table)(name, fn) e xdescribe.each`table`(name, fn)

Usa describe.skip.each per interrompere l'esecuzione di suite di test basate su dati.

describe.skip.each è disponibile con due API:

describe.skip.each(table)(name, fn)

describe.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected); // will not be run
});
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

describe.skip.each`table`(name, fn)

describe.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('will not be run', () => {
expect(a + b).toBe(expected); // will not be run
});
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test(name, fn, timeout)

Alias equivalente: it(name, fn, timeout)

Tutto ciò che ti serve in un file di test è il metodo test che esegue un test. Ad esempio, supponiamo esista una funzione inchesOfRain() che dovrebbe restituire zero. Il tuo test completo sarebbe:

test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});

Il primo argomento è il nome del test; il secondo è una funzione contenente le asserzioni da verificare. Il terzo argomento (opzionale) è timeout (in millisecondi) per specificare quanto attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Se viene restituita una promise da test, Jest attenderà il suo completamento prima di terminare il test. Ad esempio, supponiamo che fetchBeverageList() restituisca una promise che dovrebbe risolversi in una lista contenente lemon. Puoi testarlo con:

test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});

Nonostante la chiamata a test ritorni immediatamente, il test non è completo finché la promise non si risolve. Per dettagli, vedi la pagina Testing Asynchronous Code.

suggerimento

Jest attenderà anche se fornisci un argomento alla funzione di test, solitamente chiamato done. Utile per testare callback.

test.concurrent(name, fn, timeout)

Alias equivalente: it.concurrent(name, fn, timeout)

{ "message": "attenzione", "description": "The default label used for the Caution admonition (:::caution)" }

test.concurrent è considerato sperimentale - vedi qui per dettagli su funzionalità mancanti e problemi noti.

Usa test.concurrent per eseguire test in modalità concorrente.

Il primo argomento è il nome del test; il secondo argomento è una funzione asincrona che contiene le aspettative da verificare. Il terzo argomento (opzionale) è timeout (in millisecondi) per specificare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

test.concurrent('addition of 2 numbers', async () => {
expect(5 + 3).toBe(8);
});

test.concurrent('subtraction 2 numbers', async () => {
expect(5 - 3).toBe(2);
});
suggerimento

Utilizza l'opzione di configurazione maxConcurrency per impedire a Jest di eseguire contemporaneamente più test del numero specificato.

test.concurrent.each(table)(name, fn, timeout)

Disponibile anche con l'alias: it.concurrent.each(table)(name, fn, timeout)

Usa test.concurrent.each se continui a duplicare lo stesso test con dati diversi. test.each ti consente di scrivere il test una volta e passare i dati; tutti i test vengono eseguiti in modo asincrono.

test.concurrent.each è disponibile con due API:

1. test.concurrent.each(table)(name, fn, timeout)

  • table: Array di Array contenente gli argomenti passati alla funzione fn per ogni riga. Se passi un array monodimensionale di valori primitivi, internamente verrà mappato come tabella (es. [1, 2, 3] -> [[1], [2], [3]])

  • name: String titolo del blocco di test.

    • Genera titoli univoci iniettando parametricamente i valori con la formattazione printf:
      • %p - pretty-format.
      • %s- Stringa.
      • %d- Numero.
      • %i - Intero.
      • %f - Valore a virgola mobile.
      • %j - JSON.
      • %o - Oggetto.
      • %# - Indice del caso di test.
      • %$ - Numero del caso di test.
      • %% - singolo segno di percentuale ('%'). Non consuma argomenti.
  • fn: Function test da eseguire, riceverà i parametri di ogni riga come argomenti. Deve essere una funzione asincrona.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

test.concurrent.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});

2. test.concurrent.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • Prima riga con intestazioni delle colonne separate da |
    • Una o più righe successive con dati forniti come espressioni template literal usando ${value}.
  • name: String titolo del test, usa $variable per inserire i dati del test nel titolo dalle espressioni template.

    • Per inserire valori annidati puoi usare un percorso chiave (es. $variable.path.to.value, funziona solo per proprietà "proprie", ad es. $variable.constructor.name non funzionerebbe)
  • fn: Function test da eseguire. Riceve l'oggetto con i dati del test. Deve essere una funzione asincrona.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

test.concurrent.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.concurrent.only.each(table)(name, fn)

Disponibile anche con l'alias: it.concurrent.only.each(table)(name, fn)

Usa test.concurrent.only.each per eseguire solo specifici test con dati diversi in modo concorrente.

test.concurrent.only.each è disponibile con due API:

test.concurrent.only.each(table)(name, fn)

test.concurrent.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.only.each`table`(name, fn)

test.concurrent.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.concurrent.skip.each(table)(name, fn)

Disponibile anche con l'alias: it.concurrent.skip.each(table)(name, fn)

Usa test.concurrent.skip.each se vuoi interrompere l'esecuzione di una serie di test asincroni basati su dati.

test.concurrent.skip.each è disponibile in due modalità:

test.concurrent.skip.each(table)(name, fn)

test.concurrent.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.concurrent.skip.each`table`(name, fn)

test.concurrent.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.each(table)(name, fn, timeout)

Disponibile anche con gli alias: it.each(table)(name, fn) e it.each`table`(name, fn)

Usa test.each quando ripeti lo stesso test con dati diversi. test.each ti permette di scrivere il test una volta e passare i dati.

test.each è disponibile in due modalità:

1. test.each(table)(name, fn, timeout)

  • table: Array di Array contenente gli argomenti passati alla funzione fn per ogni riga. Se passi un array monodimensionale di valori primitivi, internamente verrà mappato come tabella (es. [1, 2, 3] -> [[1], [2], [3]])

  • name: String titolo del blocco di test.

    • Genera titoli unici inserendo i parametri posizionalmente con la formattazione printf:
      • %p - pretty-format.
      • %s- Stringa.
      • %d- Numero.
      • %i - Intero.
      • %f - Valore a virgola mobile.
      • %j - JSON.
      • %o - Oggetto.
      • %# - Indice del test case.
      • %$ - Numero del test case.
      • %% - singolo segno di percentuale ('%'). Non consuma argomenti.
    • Oppure genera titoli unici inserendo le proprietà dell'oggetto test case con $variable
      • Per inserire valori annidati puoi usare un percorso chiave (es. $variable.path.to.value, funziona solo per proprietà "proprie", ad es. $variable.constructor.name non funzionerebbe)
      • Puoi usare $# per inserire l'indice del test case
      • Non puoi usare $variable con la formattazione printf eccetto per %%
  • fn: Function test da eseguire, questa funzione riceverà i parametri di ogni riga come argomenti.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});
test.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

2. test.each`table`(name, fn, timeout)

  • table: Tagged Template Literal

    • Prima riga con intestazioni delle colonne separate da |
    • Una o più righe successive con dati forniti come espressioni template literal usando ${value}.
  • name: String titolo del test, usa $variable per inserire i dati del test nel titolo dalle espressioni template.

    • Per inserire valori annidati puoi usare un percorso chiave (es. $variable.path.to.value, funziona solo per proprietà "proprie", ad es. $variable.constructor.name non funzionerebbe)
  • fn: Function test da eseguire, questa funzione riceverà l'oggetto con i dati del test.

  • Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere per ogni riga prima di interrompere. Il timeout predefinito è di 5 secondi.

Esempio:

test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.failing(name, fn, timeout)

Disponibile anche con l'alias: it.failing(name, fn, timeout)

nota

Questa funzionalità è disponibile solo con il runner predefinito jest-circus.

Utilizza test.failing quando stai scrivendo un test e ti aspetti che fallisca. Questi test si comporteranno in modo opposto rispetto ai test normali: se un test failing genera errori, supererà la verifica. Se non genera errori, fallirà.

suggerimento

Puoi utilizzare questo tipo di test ad esempio quando scrivi codice seguendo l'approccio BDD. In tal caso i test non appariranno come falliti finché non supereranno la verifica. A quel punto potrai semplicemente rimuovere il modificatore failing per farli passare.

Può anche essere un modo efficace per contribuire a un progetto con test che falliscono, anche se non sai come risolvere il bug.

Esempio:

test.failing('it is not equal', () => {
expect(5).toBe(6); // this test will pass
});

test.failing('it is equal', () => {
expect(10).toBe(10); // this test will fail
});

test.failing.each(name, fn, timeout)

Disponibile anche con gli alias: it.failing.each(table)(name, fn) e it.failing.each`table`(name, fn)

nota

Questa funzionalità è disponibile solo con il runner predefinito jest-circus.

Puoi anche eseguire più test contemporaneamente aggiungendo each dopo failing.

Esempio:

test.failing.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.only.failing(name, fn, timeout)

Disponibile anche con gli alias: it.only.failing(name, fn, timeout), fit.failing(name, fn, timeout)

nota

Questa funzionalità è disponibile solo con il runner predefinito jest-circus.

Utilizza test.only.failing se vuoi eseguire solo uno specifico test che fallisce.

test.skip.failing(name, fn, timeout)

Disponibile anche con gli alias: it.skip.failing(name, fn, timeout), xit.failing(name, fn, timeout), xtest.failing(name, fn, timeout)

nota

Questa funzionalità è disponibile solo con il runner predefinito jest-circus.

Utilizza test.skip.failing se vuoi saltare l'esecuzione di uno specifico test che fallisce.

test.only(name, fn, timeout)

Disponibile anche con gli alias: it.only(name, fn, timeout), e fit(name, fn, timeout)

Durante il debug di un file di test di grandi dimensioni, spesso vorrai eseguire solo un sottoinsieme di test. Puoi utilizzare .only per specificare quali test sono gli unici che devono essere eseguiti in quel file di test.

Facoltativamente, puoi specificare un timeout (in millisecondi) per indicare quanto tempo attendere prima di interrompere. Il timeout predefinito è di 5 secondi.

Ad esempio, supponi di avere questi test:

test.only('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

Solo il test "it is raining" verrà eseguito in quel file di test, poiché è stato definito con test.only.

Normalmente non dovresti includere nel controllo del codice sorgente test che utilizzano test.only - lo utilizzerai per il debug e lo rimuoverai una volta corretti i test difettosi.

test.only.each(table)(name, fn)

Disponibile anche con gli alias: it.only.each(table)(name, fn), fit.each(table)(name, fn), it.only.each`table`(name, fn) e fit.each`table`(name, fn)

Usa test.only.each se vuoi eseguire solo test specifici con diversi set di dati.

test.only.each è disponibile con due API:

test.only.each(table)(name, fn)

test.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.only.each`table`(name, fn)

test.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip(name, fn)

Disponibile anche con gli alias: it.skip(name, fn), xit(name, fn), e xtest(name, fn)

Quando mantieni una codebase di grandi dimensioni, potresti occasionalmente trovare test temporaneamente non funzionanti. Se vuoi saltare l'esecuzione di un test senza eliminare il codice, usa test.skip.

Ad esempio, supponi di avere questi test:

test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

Verrà eseguito solo il test "sta piovendo", mentre l'altro verrà saltato grazie a test.skip.

Potresti commentare il test, ma spesso è preferibile usare test.skip perché mantiene indentazione e syntax highlighting.

test.skip.each(table)(name, fn)

Disponibile anche con gli alias: it.skip.each(table)(name, fn), xit.each(table)(name, fn), xtest.each(table)(name, fn), it.skip.each`table`(name, fn), xit.each`table`(name, fn) e xtest.each`table`(name, fn)

Usa test.skip.each per interrompere l'esecuzione di una serie di test basati su dati.

test.skip.each è disponibile con due API:

test.skip.each(table)(name, fn)

test.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip.each`table`(name, fn)

test.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.todo(name)

Disponibile anche con l'alias: it.todo(name)

Usa test.todo quando pianifichi di scrivere test futuri. Questi test saranno evidenziati nel report finale per indicare quanti test mancano.

const add = (a, b) => a + b;

test.todo('add should be associative');
suggerimento

test.todo genererà un errore se gli passi una funzione di callback. Usa invece test.skip se hai già implementato il test ma non vuoi eseguirlo.

Utilizzo con TypeScript

Traduzione Beta Non Ufficiale

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

info

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.

.each

Il modificatore .each offre diversi modi per definire una tabella di test case. Alcune API hanno limitazioni nell'inferenza dei tipi per gli argomenti passati alle funzioni di callback describe o test. Esaminiamole nel dettaglio.

nota

Gli esempi usano test.each per semplicità, ma l'inferenza dei tipi è identica in tutti i casi d'uso del modificatore .each: describe.each, test.concurrent.only.each, test.skip.each, ecc.

Array di oggetti

L'API con array di oggetti è più verbosa, ma semplifica l'inferenza dei tipi. La table può essere inline:

import {test} from '@jest/globals';

test.each([
{name: 'a', path: 'path/to/a', count: 1, write: true},
{name: 'b', path: 'path/to/b', count: 3},
])('inline table', ({name, path, count, write}) => {
// arguments are typed as expected, e.g. `write: boolean | undefined`
});

Oppure dichiarata separatamente come variabile:

import {test} from '@jest/globals';

const table = [
{a: 1, b: 2, expected: 'three', extra: true},
{a: 3, b: 4, expected: 'seven', extra: false},
{a: 5, b: 6, expected: 'eleven'},
];

test.each(table)('table as a variable', ({a, b, expected, extra}) => {
// again everything is typed as expected, e.g. `extra: boolean | undefined`
});

Array di array

Lo stile con array di array funziona bene con tabelle inline:

import {test} from '@jest/globals';

test.each([
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
])('inline table example', (a, b, expected, extra) => {
// arguments are typed as expected, e.g. `extra: boolean | undefined`
});

Tuttavia, se la tabella è dichiarata come variabile separata, va tipizzata come array di tuple per una corretta inferenza (non necessario solo se tutti gli elementi di una riga hanno lo stesso tipo):

import {test} from '@jest/globals';

const table: Array<[number, number, string, boolean?]> = [
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
];

test.each(table)('table as a variable example', (a, b, expected, extra) => {
// without the annotation types are incorrect, e.g. `a: number | string | boolean`
});

Template literal

Se tutti i valori di input sono dello stesso tipo, l'API dei template literal assegnerà correttamente i tipi agli argomenti:

import {test} from '@jest/globals';

test.each`
a | b | expected
${1} | ${2} | ${3}
${3} | ${4} | ${7}
${5} | ${6} | ${11}
`('template literal example same type', ({a, b, expected}) => {
// all arguments are of type `number` because all inputs (a, b, expected) are of type `number`
});

Se gli input hanno tipi diversi, gli argomenti verranno tipizzati come un'unione di tutti i tipi di input (ovvero il tipo delle variabili all'interno del template literal):

import {test} from '@jest/globals';

test.each`
a | b | expected
${1} | ${2} | ${'three'}
${3} | ${4} | ${'seven'}
${5} | ${6} | ${'eleven'}
`('template literal example different types', ({a, b, expected}) => {
// all arguments are of type `number | string` because some inputs (a, b) are of type `number` and some others (expected) are of type `string`
});

In alternativa, se si desidera che ogni argomento abbia il tipo corretto, è necessario fornire esplicitamente l'argomento di tipo generico:

import {test} from '@jest/globals';

test.each<{a: number; b: number; expected: string; extra?: boolean}>`
a | b | expected | extra
${1} | ${2} | ${'three'} | ${true}
${3} | ${4} | ${'seven'} | ${false}
${5} | ${6} | ${'eleven'}
`('template literal example', ({a, b, expected, extra}) => {
// all arguments are typed as expected, e.g. `a: number`, `expected: string`, `extra: boolean | undefined`
});
{ "message": "attenzione", "description": "The default label used for the Caution admonition (:::caution)" }

Tieni presente che le variabili all'interno del template literal non vengono controllate dal punto di vista dei tipi, quindi devi assicurarti che i loro tipi siano corretti.

import {test} from '@jest/globals';

test.each<{a: number; expected: string}>`
a | expected
${1} | ${'one'}
${'will not raise TS error'} | ${'two'}
${3} | ${'three'}
`('template literal with wrongly typed input', ({a, expected}) => {
// all arguments are typed as stated in the generic: `a: number`, `expected: string`
// WARNING: `a` is of type `number` but will be a string in the 2nd test case.
});