Riferimento API Test
I seguenti tipi sono utilizzati nelle firme dei tipi sottostanti
type Awaitable<T> = T | PromiseLike<T>;
type TestFunction = () => Awaitable<void>;
interface TestOptions {
/**
* Il test fallirà se impiega troppo tempo per essere eseguito
*/
timeout?: number;
/**
* Riprova il test un numero specifico di volte in caso di fallimento
*
* @default 0
*/
retry?: number;
/**
* Ripete lo stesso test più volte, anche se fallisce ogni volta.
* Se hai l'opzione "retry" e il test fallisce, utilizzerà ogni tentativo in ogni ciclo.
* Utile per il debug di fallimenti casuali.
*
* @default 0
*/
repeats?: number;
}Quando una funzione di test restituisce una promise, il runner attenderà che venga risolta per raccogliere le aspettative asincrone. Se la promise viene rifiutata, il test fallirà.
TIP
In Jest, TestFunction può anche essere di tipo (done: DoneCallback) => void. Se viene utilizzata questa forma, il test non sarà considerato concluso finché non viene chiamato done. Puoi ottenere lo stesso effetto usando una funzione async, vedi la sezione Guida alla migrazione Done Callback.
La maggior parte delle opzioni supporta sia la sintassi a punti che la sintassi a oggetti, consentendo di utilizzare lo stile che si preferisce.
import { test } from 'vitest';
test.skip('skipped test', () => {
// some logic that fails right now
});import { test } from 'vitest';
test('skipped test', { skip: true }, () => {
// some logic that fails right now
});test
- Alias:
it
test definisce un insieme di aspettative correlate. Riceve il nome del test e una funzione che contiene le asserzioni da testare.
Opzionalmente, puoi fornire un timeout (in millisecondi) per specificare il tempo massimo di attesa prima di terminare l'esecuzione del test. Il valore predefinito è di 5 secondi e può essere configurato globalmente con testTimeout.
import { expect, test } from 'vitest';
test('should work as expected', () => {
expect(Math.sqrt(4)).toBe(2);
});test.extend
- Alias:
it.extend
Usa test.extend per estendere il contesto del test con fixture personalizzate. Questo restituirà un nuovo test che è ulteriormente estendibile, quindi puoi comporre più fixture o sovrascrivere quelle esistenti estendendolo come necessario. Vedi Estendi il contesto del test per maggiori informazioni.
import { expect, test } from 'vitest';
const todos = [];
const archive = [];
const myTest = test.extend({
todos: async ({ task }, use) => {
todos.push(1, 2, 3);
await use(todos);
todos.length = 0;
},
archive,
});
myTest('add item', ({ todos }) => {
expect(todos.length).toBe(3);
todos.push(4);
expect(todos.length).toBe(4);
});test.skip
- Alias:
it.skip
Se vuoi saltare l'esecuzione di determinati test, ma non vuoi eliminare il codice per qualsiasi motivo, puoi usare test.skip per impedirne l'esecuzione.
import { assert, test } from 'vitest';
test.skip('skipped test', () => {
// Test skipped, no error
assert.equal(Math.sqrt(4), 3);
});Puoi anche saltare il test invocando skip sul suo contesto dinamicamente:
import { assert, test } from 'vitest';
test('skipped test', context => {
context.skip();
// Test skipped, no error
assert.equal(Math.sqrt(4), 3);
});test.skipIf
- Alias:
it.skipIf
In alcuni casi, potresti eseguire i test più volte in ambienti diversi, e alcuni di essi potrebbero essere specifici per un determinato ambiente. Invece di racchiudere il codice del test all'interno di un blocco if, è possibile utilizzare test.skipIf per saltare il test qualora la condizione specificata sia valutata come truthy.
import { assert, test } from 'vitest';
const isDev = process.env.NODE_ENV === 'development';
test.skipIf(isDev)('prod only test', () => {
// questo test viene eseguito solo in produzione
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
test.runIf
- Alias:
it.runIf
Contrario di test.skipIf.
import { assert, test } from 'vitest';
const isDev = process.env.NODE_ENV === 'development';
test.runIf(isDev)('dev only test', () => {
// questo test viene eseguito solo in sviluppo
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
test.only
- Alias:
it.only
Usa test.only per eseguire solo determinati test all'interno di una suite. Questo è utile per il debug.
Opzionalmente, puoi fornire un timeout (in millisecondi) per specificare il tempo massimo di attesa prima di terminare l'esecuzione del test. Il valore predefinito è di 5 secondi e può essere configurato globalmente con testTimeout.
import { assert, test } from 'vitest';
test.only('test', () => {
// Solo questo test (e altri contrassegnati con only) vengono eseguiti
assert.equal(Math.sqrt(4), 2);
});A volte è molto utile eseguire test only in un determinato file, ignorando tutti gli altri test dell'intera suite, alterando così l'output.
Per fare ciò, esegui vitest specificando il file contenente i test in questione.
# vitest interesting.test.tstest.concurrent
- Alias:
it.concurrent
test.concurrent marca i test consecutivi da eseguire in parallelo. Riceve il nome del test, una funzione asincrona con i test da eseguire e un timeout opzionale (in millisecondi).
import { describe, test } from 'vitest';
// I due test contrassegnati con concurrent saranno eseguiti in parallelo
describe('suite', () => {
test('serial test', async () => {
/* ... */
});
test.concurrent('concurrent test 1', async () => {
/* ... */
});
test.concurrent('concurrent test 2', async () => {
/* ... */
});
});test.skip, test.only e test.todo funzionano con i test concurrenti. Tutte le seguenti combinazioni sono valide:
test.concurrent(/* ... */);
test.skip.concurrent(/* ... */); // or test.concurrent.skip(/* ... */)
test.only.concurrent(/* ... */); // or test.concurrent.only(/* ... */)
test.todo.concurrent(/* ... */); // or test.concurrent.todo(/* ... */)Quando si eseguono test concurrenti, Snapshots e Assertions devono usare expect dal Contesto del test locale per garantire l'identificazione del test corretto.
test.concurrent('test 1', async ({ expect }) => {
expect(foo).toMatchSnapshot();
});
test.concurrent('test 2', async ({ expect }) => {
expect(foo).toMatchSnapshot();
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
test.sequential
- Alias:
it.sequential
test.sequential contrassegna un test come sequenziale. Questo è utile se si desidera eseguire i test in sequenza all'interno di describe.concurrent o con l'opzione della riga di comando --sequence.concurrent.
import { describe, test } from 'vitest';
// con l'opzione di configurazione { sequence: { concurrent: true } }
test('concurrent test 1', async () => {
/* ... */
});
test('concurrent test 2', async () => {
/* ... */
});
test.sequential('sequential test 1', async () => {
/* ... */
});
test.sequential('sequential test 2', async () => {
/* ... */
});
// all'interno della suite concorrente
describe.concurrent('suite', () => {
test('concurrent test 1', async () => {
/* ... */
});
test('concurrent test 2', async () => {
/* ... */
});
test.sequential('sequential test 1', async () => {
/* ... */
});
test.sequential('sequential test 2', async () => {
/* ... */
});
});test.todo
- Alias:
it.todo
Usa test.todo per creare segnaposto di test da implementare in seguito. Verrà visualizzata una voce nel report dei test, indicando quanti test devono ancora essere implementati.
// Verrà visualizzata una voce nel report per questo test
test.todo('unimplemented test');test.fails
- Alias:
it.fails
Usa test.fails per indicare che un'asserzione fallirà intenzionalmente.
import { expect, test } from 'vitest';
function myAsyncFunc() {
return new Promise(resolve => resolve(1));
}
test.fails('fail test', async () => {
await expect(myAsyncFunc()).rejects.toBe(1);
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
test.each
- Alias:
it.each
TIP
Mentre test.each è fornito per la compatibilità con Jest, Vitest ha anche test.for con una funzionalità aggiuntiva per integrare TestContext.
Usa test.each quando devi eseguire lo stesso test con input diversi. È possibile inserire parametri con formattazione printf nel nome del test, nell'ordine dei parametri della funzione di test.
%s: stringa%d: numero%i: intero%f: valore a virgola mobile%j: json%o: oggetto%#: indice del caso di test%%: singolo segno di percentuale ('%')
import { expect, test } from 'vitest';
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('add(%i, %i) -> %i', (a, b, expected) => {
expect(a + b).toBe(expected);
});
// questo restituirà
// ✓ add(1, 1) -> 2
// ✓ add(1, 2) -> 3
// ✓ add(2, 1) -> 3Puoi anche accedere alle proprietà dell'oggetto con il prefisso $, se stai usando oggetti come argomenti:
test.each([
{ a: 1, b: 1, expected: 2 },
{ a: 1, b: 2, expected: 3 },
{ a: 2, b: 1, expected: 3 },
])('add($a, $b) -> $expected', ({ a, b, expected }) => {
expect(a + b).toBe(expected);
});
// questo restituirà
// ✓ add(1, 1) -> 2
// ✓ add(1, 2) -> 3
// ✓ add(2, 1) -> 3Puoi anche accedere agli attributi dell'oggetto con ., se stai usando oggetti come argomenti:
test.each`
a | b | expected
${{ val: 1 }} | ${'b'} | ${'1b'}
${{ val: 2 }} | ${'b'} | ${'2b'}
${{ val: 3 }} | ${'b'} | ${'3b'}
`('add($a.val, $b) -> $expected', ({ a, b, expected }) => {
expect(a.val + b).toBe(expected);
});
// questo restituirà
// ✓ add(1, b) -> 1b
// ✓ add(2, b) -> 2b
// ✓ add(3, b) -> 3bA partire da Vitest 0.25.3, puoi anche usare la tabella delle stringhe modello.
- La prima riga dovrebbe contenere i nomi delle colonne, separati da
|; - Una o più righe successive di dati forniti come espressioni letterali modello usando la sintassi
${value}.
import { expect, test } from 'vitest';
test.each`
a | b | expected
${1} | ${1} | ${2}
${'a'} | ${'b'} | ${'ab'}
${[]} | ${'b'} | ${'b'}
${{}} | ${'b'} | ${'[object Object]b'}
${{ asd: 1 }} | ${'b'} | ${'[object Object]b'}
`('returns $expected when $a is added $b', ({ a, b, expected }) => {
expect(a + b).toBe(expected);
});TIP
Vitest elabora $values con il metodo format di chai. Se il valore viene troncato eccessivamente, puoi aumentare chaiConfig.truncateThreshold nel tuo file di configurazione.
WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
test.for
- Alias:
it.for
Alternativa a test.each per fornire TestContext.
La differenza da test.each è come il caso array viene fornito negli argomenti. Gli altri casi non array (incluso l'uso di template string) funzionano esattamente allo stesso modo.
// `each` espande il caso array
test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('add(%i, %i) -> %i', (a, b, expected) => {
expect(a + b).toBe(expected);
});
// `for` non espande il caso array
test.for([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('add(%i, %i) -> %i', ([a, b, expected]) => {
expect(a + b).toBe(expected);
});Il 2° argomento è TestContext e può essere utilizzato per snapshot concorrenti, ad esempio:
test.concurrent.for([
[1, 1],
[1, 2],
[2, 1],
])('add(%i, %i)', ([a, b], { expect }) => {
expect(a + b).matchSnapshot();
});bench
- Tipo:
(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void
bench definisce un benchmark. In Vitest, un benchmark è una funzione che definisce una serie di operazioni. Vitest esegue questa funzione più volte per visualizzare diversi risultati di performance.
Vitest utilizza internamente la libreria tinybench, ereditandone tutte le opzioni, che possono essere utilizzate come terzo argomento.
import { bench } from 'vitest';
bench(
'normal sorting',
() => {
const x = [1, 5, 4, 2, 3];
x.sort((a, b) => {
return a - b;
});
},
{ time: 1000 }
);export interface Options {
/**
* Tempo necessario per l'esecuzione di un'attività di benchmark (in millisecondi)
* @default 500
*/
time?: number;
/**
* Numero di ripetizioni dell'attività, anche se l'opzione time è scaduta
* @default 10
*/
iterations?: number;
/**
* Funzione per ottenere il timestamp corrente in millisecondi
*/
now?: () => number;
/**
* Un segnale AbortSignal per interrompere il benchmark
*/
signal?: AbortSignal;
/**
* Lancia un errore se un'attività fallisce (gli eventi non funzioneranno se vero)
*/
throws?: boolean;
/**
* Tempo di riscaldamento (in millisecondi)
* @default 100ms
*/
warmupTime?: number;
/**
* Cicli di riscaldamento
* @default 5
*/
warmupIterations?: number;
/**
* Funzione di setup da eseguire prima di ogni attività di benchmark (ciclo)
*/
setup?: Hook;
/**
* Funzione di teardown da eseguire dopo ogni attività di benchmark (ciclo)
*/
teardown?: Hook;
}Dopo l'esecuzione del caso di test, le informazioni sulla struttura di output sono le seguenti:
name hz min max mean p75 p99 p995 p999 rme samples
· normal sorting 6,526,368.12 0.0001 0.3638 0.0002 0.0002 0.0002 0.0002 0.0004 ±1.41% 652638export interface TaskResult {
/*
* l'ultimo errore che è stato lanciato durante l'esecuzione del compito
*/
error?: unknown;
/**
* La quantità di tempo in millisecondi per eseguire il compito di benchmark (ciclo).
*/
totalTime: number;
/**
* il valore minimo nei campioni
*/
min: number;
/**
* il valore massimo nei campioni
*/
max: number;
/**
* il numero di operazioni al secondo
*/
hz: number;
/**
* quanto tempo impiega ciascuna operazione (ms)
*/
period: number;
/**
* campioni di tempo di iterazione di ciascun compito (ms)
*/
samples: number[];
/**
* media/media dei campioni (stima della media della popolazione)
*/
mean: number;
/**
* varianza dei campioni (stima della varianza della popolazione)
*/
variance: number;
/**
* deviazione standard dei campioni (stima della deviazione standard della popolazione)
*/
sd: number;
/**
* errore standard della media (altrimenti nota come deviazione standard della distribuzione campionaria della media del campione)
*/
sem: number;
/**
* gradi di libertà
*/
df: number;
/**
* valore critico dei campioni
*/
critical: number;
/**
* margine di errore
*/
moe: number;
/**
* margine di errore relativo
*/
rme: number;
/**
* deviazione assoluta mediana
*/
mad: number;
/**
* p50/percentile mediano
*/
p50: number;
/**
* percentile p75
*/
p75: number;
/**
* percentile p99
*/
p99: number;
/**
* percentile p995
*/
p995: number;
/**
* percentile p999
*/
p999: number;
}bench.skip
- Tipo:
(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void
Puoi usare la sintassi bench.skip per saltare l'esecuzione di determinati benchmark.
import { bench } from 'vitest';
bench.skip('normal sorting', () => {
const x = [1, 5, 4, 2, 3];
x.sort((a, b) => {
return a - b;
});
});bench.only
- Tipo:
(name: string | Function, fn: BenchFunction, options?: BenchOptions) => void
Usa bench.only per eseguire solo determinati benchmark all'interno di una suite. Questo è utile per il debug.
import { bench } from 'vitest';
bench.only('normal sorting', () => {
const x = [1, 5, 4, 2, 3];
x.sort((a, b) => {
return a - b;
});
});bench.todo
- Tipo:
(name: string | Function) => void
Usa bench.todo per creare segnaposto di benchmark da implementare in seguito.
import { bench } from 'vitest';
bench.todo('unimplemented test');describe
Quando si usa test o bench a livello superiore di un file, questi vengono raccolti come parte della suite implicita per quel file. Utilizzando describe puoi definire una nuova suite nel contesto corrente, intesa come un insieme di test o benchmark correlati, eventualmente annidata con altre suite. Una suite ti permette di organizzare i tuoi test e benchmark in modo che i report siano più chiari e leggibili.
// basic.spec.ts
// organizzazione dei test
import { describe, expect, test } from 'vitest';
const person = {
isActive: true,
age: 32,
};
describe('person', () => {
test('person is defined', () => {
expect(person).toBeDefined();
});
test('is active', () => {
expect(person.isActive).toBeTruthy();
});
test('age limit', () => {
expect(person.age).toBeLessThanOrEqual(32);
});
});// basic.bench.ts
// organizzazione dei benchmark
import { bench, describe } from 'vitest';
describe('sort', () => {
bench('normal', () => {
const x = [1, 5, 4, 2, 3];
x.sort((a, b) => {
return a - b;
});
});
bench('reverse', () => {
const x = [1, 5, 4, 2, 3];
x.reverse().sort((a, b) => {
return a - b;
});
});
});Puoi anche annidare blocchi describe se hai una gerarchia di test o benchmark:
import { describe, expect, test } from 'vitest';
function numberToCurrency(value: number | string) {
if (typeof value !== 'number') {
throw new TypeError('Value must be a number');
}
return value
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
describe('numberToCurrency', () => {
describe('given an invalid number', () => {
test('composed of non-numbers to throw error', () => {
expect(() => numberToCurrency('abc')).toThrowError();
});
});
describe('given a valid number', () => {
test('returns the correct currency format', () => {
expect(numberToCurrency(10000)).toBe('10,000.00');
});
});
});describe.skip
- Alias:
suite.skip
Usa describe.skip in una suite per evitare di eseguire un particolare blocco describe.
import { assert, describe, test } from 'vitest';
describe.skip('skipped suite', () => {
test('sqrt', () => {
// Suite skipped, no error
assert.equal(Math.sqrt(4), 3);
});
});describe.skipIf
- Alias:
suite.skipIf
In alcuni casi, potresti voler eseguire le suite in ambienti diversi, e alcune di esse potrebbero essere specifiche per un determinato ambiente. Invece di racchiudere la suite all'interno di un blocco if, puoi usare describe.skipIf per saltare la suite quando la condizione specificata è truthy (vera).
import { describe, test } from 'vitest';
const isDev = process.env.NODE_ENV === 'development';
describe.skipIf(isDev)('prod only test', () => {
// this test only runs in production
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
describe.runIf
- Alias:
suite.runIf
Opposto di describe.skipIf.
import { assert, describe, test } from 'vitest';
const isDev = process.env.NODE_ENV === 'development';
describe.runIf(isDev)('dev only test suite', () => {
// this test suite only runs in development
});WARNING
Non puoi utilizzare questa sintassi quando utilizzi Vitest come type checker.
describe.only
- Tipo:
(name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
Usa describe.only per eseguire solo determinate suite.
import { assert, describe, test } from 'vitest';
// Only this suite (and others marked with only) are run
describe.only('suite', () => {
test('sqrt', () => {
assert.equal(Math.sqrt(4), 3);
});
});
describe('other suite', () => {
// ... will be skipped
});A volte è utile eseguire solo i test contrassegnati con only in un determinato file, escludendo tutti gli altri test della suite, per avere un output più chiaro.
Per fare ciò, esegui vitest con il file specificato contenente i test in questione.
# vitest interesting.test.tsdescribe.concurrent
- Alias:
suite.concurrent
describe.concurrent esegue tutte le suite e i test interni in parallelo
import { describe, test } from 'vitest';
// Tutte le suite e i test all'interno di questa suite verranno eseguiti in parallelo
describe.concurrent('suite', () => {
test('concurrent test 1', async () => {
/* ... */
});
describe('concurrent suite 2', async () => {
test('concurrent test inner 1', async () => {
/* ... */
});
test('concurrent test inner 2', async () => {
/* ... */
});
});
test.concurrent('concurrent test 3', async () => {
/* ... */
});
});.skip, .only e .todo funzionano con le suite concorrenti. Tutte le seguenti combinazioni sono valide:
describe.concurrent(/* ... */);
describe.skip.concurrent(/* ... */); // or describe.concurrent.skip(/* ... */)
describe.only.concurrent(/* ... */); // or describe.concurrent.only(/* ... */)
describe.todo.concurrent(/* ... */); // or describe.concurrent.todo(/* ... */)Quando si eseguono test concorrenti, le asserzioni e gli snapshot devono utilizzare expect dal Contesto di Test locale, per assicurarsi che venga individuato il test corretto.
describe.concurrent('suite', () => {
test('concurrent test 1', async ({ expect }) => {
expect(foo).toMatchSnapshot();
});
test('concurrent test 2', async ({ expect }) => {
expect(foo).toMatchSnapshot();
});
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
describe.sequential
- Alias:
suite.sequential
describe.sequential in una suite contrassegna ogni test come sequenziale. Questo è utile se si desidera eseguire test in sequenza all'interno di un blocco describe.concurrent o utilizzando l'opzione da riga di comando --sequence.concurrent.
import { describe, test } from 'vitest';
describe.concurrent('suite', () => {
test('concurrent test 1', async () => {
/* ... */
});
test('concurrent test 2', async () => {
/* ... */
});
describe.sequential('', () => {
test('sequential test 1', async () => {
/* ... */
});
test('sequential test 2', async () => {
/* ... */
});
});
});describe.shuffle
- Alias:
suite.shuffle
Vitest offre la possibilità di eseguire tutti i test in ordine casuale tramite il flag CLI --sequence.shuffle o l'opzione di configurazione sequence.shuffle; tuttavia, se si desidera eseguire solo una parte della suite di test in ordine casuale, è possibile contrassegnare quella sezione specifica.
import { describe, test } from 'vitest';
describe.shuffle('suite', () => {
test('random test 1', async () => {
/* ... */
});
test('random test 2', async () => {
/* ... */
});
test('random test 3', async () => {
/* ... */
});
});
// order depends on sequence.seed option in config (Date.now() by default).skip, .only e .todo funzionano con le suite casuali.
WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
describe.todo
- Alias:
suite.todo
Usa describe.todo per creare bozze di suite da implementare in seguito. Verrà mostrata una voce nel report per i test, in modo da sapere quanti test devi ancora implementare.
// An entry will be shown in the report for this suite
describe.todo('unimplemented suite');describe.each
- Alias:
suite.each
Usa describe.each se hai più di un test che dipende dagli stessi dati.
import { describe, expect, test } from 'vitest';
describe.each([
{ a: 1, b: 1, expected: 2 },
{ a: 1, b: 2, expected: 3 },
{ a: 2, b: 1, expected: 3 },
])('describe object 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);
});
});A partire da Vitest 0.25.3, puoi anche usare la tabella di stringhe modello.
- La prima riga dovrebbe contenere i nomi delle colonne, separati da
|; - Una o più righe successive di dati forniti come espressioni di template literal usando la sintassi
${value}.
import { describe, expect, test } from 'vitest';
describe.each`
a | b | expected
${1} | ${1} | ${2}
${'a'} | ${'b'} | ${'ab'}
${[]} | ${'b'} | ${'b'}
${{}} | ${'b'} | ${'[object Object]b'}
${{ asd: 1 }} | ${'b'} | ${'[object Object]b'}
`('describe template string add($a, $b)', ({ a, b, expected }) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
});WARNING
Non puoi usare questa sintassi quando usi Vitest come type checker.
Setup and Teardown
Queste funzioni ti permettono di agganciarti al "lifecycle" dei test per evitare di ripetere il codice di configurazione e pulizia. Si applicano al contesto corrente: al file, se utilizzate a livello più alto, o alla suite corrente, se inserite all'interno di un blocco describe. Questi hook non vengono eseguiti quando si usa Vitest come type checker.
beforeEach
- Tipo:
beforeEach(fn: () => Awaitable<void>, timeout?: number)
Registra una callback che verrà eseguita prima di ciascun test nel contesto corrente. Se la funzione restituisce una Promise, Vitest attenderà che la Promise si risolva prima di eseguire il test.
Opzionalmente, puoi passare un "timeout" (in millisecondi) che definisce per quanto tempo aspettare prima di terminare. Il valore predefinito è 5 secondi.
import { beforeEach } from 'vitest';
beforeEach(async () => {
// Clear mocks and add some testing data before each test run
await stopMocking();
await addUser({ name: 'John' });
});Qui, beforeEach assicura che l'utente venga aggiunto prima di ogni test.
beforeEach accetta anche una funzione di cleanup opzionale (funzionalità equivalente a afterEach).
import { beforeEach } from 'vitest';
beforeEach(async () => {
// called once before each test run
await prepareSomething();
// clean up function, called once after each test run
return async () => {
await resetSomething();
};
});afterEach
- Tipo:
afterEach(fn: () => Awaitable<void>, timeout?: number)
Registra una callback che verrà eseguita al termine di ciascun test nel contesto corrente. Se la funzione restituisce una Promise, Vitest attenderà che la Promise si risolva prima di continuare.
Opzionalmente, puoi fornire un "timeout" (in millisecondi) per specificare per quanto tempo aspettare prima di terminare. Il valore predefinito è 5 secondi.
import { afterEach } from 'vitest';
afterEach(async () => {
await clearTestingData(); // clear testing data after each test run
});Qui, afterEach assicura che i dati per i test vengano cancellati dopo l'esecuzione di ciascun test.
TIP
Vitest 1.3.0 ha aggiunto l'hook onTestFinished. Puoi chiamarlo durante l'esecuzione del test per ripulire qualsiasi stato dopo che il test è terminato.
beforeAll
- Tipo:
beforeAll(fn: () => Awaitable<void>, timeout?: number)
Registra una callback che verrà eseguita una sola volta, prima dell'inizio di tutti i test nel contesto corrente. Se la funzione restituisce una Promise, Vitest attenderà che la Promise si risolva prima di eseguire i test.
Opzionalmente, puoi fornire un "timeout" (in millisecondi) per specificare per quanto tempo aspettare prima di terminare. Il valore predefinito è 5 secondi.
import { beforeAll } from 'vitest';
beforeAll(async () => {
await startMocking(); // called once before all tests run
});Qui beforeAll assicura che i dati di mock siano impostati prima dell'esecuzione dei test.
beforeAll accetta anche una funzione di cleanup opzionale (funzionalità equivalente a afterAll).
import { beforeAll } from 'vitest';
beforeAll(async () => {
// called once before all tests run
await startMocking();
// clean up function, called once after all tests run
return async () => {
await stopMocking();
};
});afterAll
- Tipo:
afterAll(fn: () => Awaitable<void>, timeout?: number)
Registra una callback che verrà eseguita una sola volta, al termine di tutti i test nel contesto corrente. Se la funzione restituisce una Promise, Vitest attenderà che la Promise si risolva prima di continuare.
Opzionalmente, puoi fornire un "timeout" (in millisecondi) per specificare per quanto tempo aspettare prima di terminare. Il valore predefinito è 5 secondi.
import { afterAll } from 'vitest';
afterAll(async () => {
await stopMocking(); // this method is called after all tests run
});Qui afterAll assicura che il metodo stopMocking venga chiamato dopo che tutti i test sono stati eseguiti.
Hook di test
Vitest fornisce alcuni hook che è possibile chiamare durante l'esecuzione del test per pulire lo stato al termine dell'esecuzione del test.
WARNING
Questi hook genereranno un errore se vengono chiamati al di fuori del corpo del test.
onTestFinished
Questo hook viene sempre chiamato dopo che il test ha terminato l'esecuzione. Viene chiamato dopo gli hook afterEach perché possono influenzare il risultato del test. Riceve un oggetto TaskResult con il risultato corrente del test.
import { onTestFinished, test } from 'vitest';
test('esegue una query', () => {
const db = connectDb();
onTestFinished(() => db.close());
db.query('SELECT * FROM users');
});WARNING
Se si eseguono test simultaneamente, è necessario utilizzare sempre l'hook onTestFinished dal contesto del test poiché Vitest non tiene traccia dei test simultanei negli hook globali:
import { test from 'vitest'
test.concurrent('esegue una query', ({ onTestFinished }) => {
const db = connectDb()
onTestFinished(()(() => db.close())
db.query('SELECT * FROM users')
})Questo hook è particolarmente utile quando si crea una logica riutilizzabile:
// questo può essere in un file separato
function getTestDb() {
const db = connectMockedDb()
onTestFinished(()(() => db.close())
return db
}
test('esegue una query utente', async () => {
const db = getTestDb()
expect(await db.query('SELECT * from users').perform()).toEqual([])
})
test('esegue una query sull'organizzazione', async () => {
const db = getTestDb()
expect(await db.query('SELECT * from organizations').perform()).toEqual([])
})TIP
Questo hook viene sempre chiamato in ordine inverso e non è influenzato dall'opzione sequence.hooks.
onTestFailed
Questo hook viene chiamato solo dopo che il test non è riuscito. Viene chiamato dopo gli hook afterEach perché possono influenzare il risultato del test. Riceve un oggetto TaskResult con il risultato corrente del test. Questo hook è utile per il debug.
import { onTestFailed, test from 'vitest'
test('esegue una query', () => {
const db = connectDb()
onTestFailed((e) => {
console.log(e.result.errors)
})
db.query('SELECT * FROM users')
})WARNING
Se si eseguono test simultaneamente, è necessario utilizzare sempre l'hook onTestFailed dal contesto del test poiché Vitest non tiene traccia dei test simultanei negli hook globali:
import { test from 'vitest'
test.concurrent('esegue una query', ({ onTestFailed }) => {
const db = connectDb()
onTestFailed((result) => {
console.log(result.errors)
})
db.query('SELECT * FROM users')
})