Skip to content
Vitest 3
Main Navigation Guida & APIConfigurazioneModalità BrowserAPI avanzata
3.2.0
2.1.9
1.6.1
0.34.6

Italiano

English
简体中文
繁體中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Polski
Türkçe
čeština
magyar

Italiano

English
简体中文
繁體中文
Español
Français
Русский
Português – Brasil
Deutsch
日本語
한국어
Polski
Türkçe
čeština
magyar

Aspetto

Sidebar Navigation

Introduzione

Perché Vitest

Per Iniziare

Caratteristiche

Configurazione di Vitest

API

Riferimento API di test

Funzioni Mock

Vi

expect

expectTypeOf

assert

assertType

Guida

Interfaccia a Riga di Comando

Filtro dei Test

Progetti di Test

Reporter

Copertura

Snapshot

Mocking

Parallelismo

Tipi di Test

Vitest UI

Test nel Codice Sorgente

Contesto di Test

Annotazioni dei Test

Ambiente di Test

Estensione dei Matcher

Integrazioni IDE

Debugging

Errori Comuni

Guida alla Migrazione

Migrazione a Vitest 3.0

Migrazione da Jest

Prestazioni

Profilazione delle prestazioni dei test

Ottimizzare le Prestazioni

Modalità Browser

API Avanzate

Confronto con Altri Test Runner

In questa pagina

Reporter ​

Vitest offre diversi reporter integrati per visualizzare l'output dei test in vari formati, oltre alla possibilità di utilizzare reporter personalizzati. È possibile selezionare i reporter tramite l'opzione da riga di comando --reporter o includendo una proprietà reporters nel file di configurazione. Se non viene specificato alcun reporter, Vitest utilizzerà il reporter default descritto di seguito.

Utilizzo dei reporter da riga di comando:

bash
npx vitest --reporter=verbose

Utilizzo dei reporter tramite vitest.config.ts:

ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    reporters: ['verbose'],
  },
});

Alcuni reporter possono essere personalizzati passando opzioni aggiuntive. Le opzioni specifiche per ciascun reporter sono descritte nelle sezioni seguenti.

ts
export default defineConfig({
  test: {
    reporters: ['default', ['junit', { suiteName: 'UI tests' }]],
  },
});

Output dei Reporter ​

Per impostazione predefinita, i reporter di Vitest stamperanno l'output nel terminale. Quando si utilizzano i reporter json, html o junit, è possibile scrivere l'output dei test in un file includendo un'opzione di configurazione outputFile nel file di configurazione di Vite o tramite CLI.

bash
npx vitest --reporter=json --outputFile=./test-output.json
ts
export default defineConfig({
  test: {
    reporters: ['json'],
    outputFile: './test-output.json',
  },
});

Combinazione di Reporter ​

È possibile utilizzare più reporter contemporaneamente per stampare i risultati dei test in diversi formati. Ad esempio:

bash
npx vitest --reporter=json --reporter=default
ts
export default defineConfig({
  test: {
    reporters: ['json', 'default'],
    outputFile: './test-output.json',
  },
});

L'esempio precedente stamperà i risultati del test nel terminale con lo stile predefinito e li scriverà in formato JSON nel file di output specificato.

Utilizzando più reporter, è possibile designare anche più file di output, come segue:

ts
export default defineConfig({
  test: {
    reporters: ['junit', 'json', 'verbose'],
    outputFile: {
      junit: './junit-report.xml',
      json: './json-report.json',
    },
  },
});

Questo esempio genererà report JSON e XML separati e stamperà un report dettagliato nel terminale.

Reporter Integrati ​

Reporter Predefinito ​

Per impostazione predefinita (ovvero, se non viene specificato alcun reporter), Vitest visualizzerà un riepilogo dei test in esecuzione e il loro stato in basso. Una volta che una suite è completata, il suo stato verrà visualizzato in cima al riepilogo.

È possibile disabilitare il riepilogo configurando il reporter:

ts
export default defineConfig({
  test: {
    reporters: [['default', { summary: false }]],
  },
});

Esempio di output per i test in corso:

bash
 ✓ test/example-1.test.ts (5 tests | 1 skipped) 306ms
 ✓ test/example-2.test.ts (5 tests | 1 skipped) 307ms

 ❯ test/example-3.test.ts 3/5
 ❯ test/example-4.test.ts 1/5

 Test Files 2 passed (4)
      Tests 10 passed | 3 skipped (65)
   Start at 11:01:36
   Duration 2.00s

Output finale dopo che i test sono terminati:

bash
 ✓ test/example-1.test.ts (5 tests | 1 skipped) 306ms
 ✓ test/example-2.test.ts (5 tests | 1 skipped) 307ms
 ✓ test/example-3.test.ts (5 tests | 1 skipped) 307ms
 ✓ test/example-4.test.ts (5 tests | 1 skipped) 307ms

 Test Files  4 passed (4)
      Tests  16 passed | 4 skipped (20)
   Start at  12:34:32
   Duration  1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)

Reporter Basic ​

Il reporter basic è equivalente al reporter default senza il summary.

bash
npx vitest --reporter=basic
ts
export default defineConfig({
  test: {
    reporters: ['basic'],
  },
});

Esempio di output con il reporter basic:

bash
✓ __tests__/file1.test.ts (2) 725ms
✓ __tests__/file2.test.ts (2) 746ms

 Test Files  2 passed (2)
      Tests  4 passed (4)
   Start at  12:34:32
   Duration  1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)

Reporter Dettagliato ​

Il reporter dettagliato è simile al reporter default, ma visualizza anche ogni singolo test dopo che la suite è terminata. Visualizza anche i test attualmente in esecuzione che impiegano più tempo di slowTestThreshold. Similmente al reporter default, è possibile disabilitare il riepilogo configurando il reporter.

bash
npx vitest --reporter=verbose
ts
export default defineConfig({
  test: {
    reporters: [['verbose', { summary: false }]],
  },
});

Esempio di output per i test in corso con slowTestThreshold: 300 predefinito:

bash
 ✓ __tests__/example-1.test.ts (2) 725ms
   ✓ first test file (2) 725ms
     ✓ 2 + 2 should equal 4
     ✓ 4 - 2 should equal 2

 ❯ test/example-2.test.ts 3/5
   ↳ should run longer than three seconds 1.57s
 ❯ test/example-3.test.ts 1/5

 Test Files 2 passed (4)
      Tests 10 passed | 3 skipped (65)
   Start at 11:01:36
   Duration 2.00s

Esempio di output finale del terminale per una suite di test superata:

bash
✓ __tests__/file1.test.ts (2) 725ms
   ✓ first test file (2) 725ms
     ✓ 2 + 2 should equal 4
     ✓ 4 - 2 should equal 2
✓ __tests__/file2.test.ts (2) 746ms
  ✓ second test file (2) 746ms
    ✓ 1 + 1 should equal 2
    ✓ 2 - 1 should equal 1

 Test Files  2 passed (2)
      Tests  4 passed (4)
   Start at  12:34:32
   Duration  1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)

Reporter a Punti ​

Stampa un singolo punto per ogni test completato per fornire un output minimo pur mostrando tutti i test eseguiti. Vengono forniti dettagli solo per i test falliti, insieme al riepilogo della suite fornito dal reporter basic.

bash
npx vitest --reporter=dot
ts
export default defineConfig({
  test: {
    reporters: ['dot'],
  },
});

Esempio di output del terminale per una suite di test superata:

bash
....

 Test Files  2 passed (2)
      Tests  4 passed (4)
   Start at  12:34:32
   Duration  1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)

Reporter JUnit ​

Genera un report dei risultati dei test in formato XML JUnit. Può essere stampato nel terminale o scritto in un file XML utilizzando l'opzione di configurazione outputFile.

bash
npx vitest --reporter=junit
ts
export default defineConfig({
  test: {
    reporters: ['junit'],
  },
});

Esempio di un report XML JUnit:

xml
<?xml version="1.0" encoding="UTF-8" ?>
<testsuites name="vitest tests" tests="2" failures="1" errors="0" time="0.503">
    <testsuite name="__tests__/test-file-1.test.ts" timestamp="2023-10-19T17:41:58.580Z" hostname="My-Computer.local" tests="2" failures="1" errors="0" skipped="0" time="0.013">
        <testcase classname="__tests__/test-file-1.test.ts" name="first test file &gt; 2 + 2 should equal 4" time="0.01">
            <failure message="expected 5 to be 4 // Object.is equality" type="AssertionError">
AssertionError: expected 5 to be 4 // Object.is equality
 ❯ __tests__/test-file-1.test.ts:20:28
            </failure>
        </testcase>
        <testcase classname="__tests__/test-file-1.test.ts" name="first test file &gt; 4 - 2 should equal 2" time="0">
        </testcase>
    </testsuite>
</testsuites>

L'XML generato contiene i tag annidati testsuites e testcase. Questi possono anche essere personalizzati tramite le opzioni del reporter suiteName e classnameTemplate. classnameTemplate può essere una stringa di template o una funzione.

I segnaposto supportati per l'opzione classnameTemplate sono:

  • filename
  • filepath
ts
export default defineConfig({
  test: {
    reporters: [
      [
        'junit',
        {
          suiteName: 'custom suite name',
          classnameTemplate: 'filename:{filename} - filepath:{filepath}',
        },
      ],
    ],
  },
});

Reporter JSON ​

Genera un report dei risultati dei test in un formato JSON compatibile con l'opzione --json di Jest. Può essere stampato nel terminale o scritto in un file utilizzando l'opzione di configurazione outputFile.

bash
npx vitest --reporter=json
ts
export default defineConfig({
  test: {
    reporters: ['json'],
  },
});

Esempio di un report JSON:

json
{
  "numTotalTestSuites": 4,
  "numPassedTestSuites": 2,
  "numFailedTestSuites": 1,
  "numPendingTestSuites": 1,
  "numTotalTests": 4,
  "numPassedTests": 1,
  "numFailedTests": 1,
  "numPendingTests": 1,
  "numTodoTests": 1,
  "startTime": 1697737019307,
  "success": false,
  "testResults": [
    {
      "assertionResults": [
        {
          "ancestorTitles": ["", "first test file"],
          "fullName": " first test file 2 + 2 should equal 4",
          "status": "failed",
          "title": "2 + 2 should equal 4",
          "duration": 9,
          "failureMessages": ["expected 5 to be 4 // Object.is equality"],
          "location": {
            "line": 20,
            "column": 28
          },
          "meta": {}
        }
      ],
      "startTime": 1697737019787,
      "endTime": 1697737019797,
      "status": "failed",
      "message": "",
      "name": "/root-directory/__tests__/test-file-1.test.ts"
    }
  ],
  "coverageMap": {}
}

INFO

A partire da Vitest 3, il reporter JSON include le informazioni sulla copertura in coverageMap se la copertura è abilitata.

Reporter HTML ​

Genera un file HTML per visualizzare i risultati dei test tramite una GUI interattiva. Dopo che il file è stato generato, Vitest manterrà un server di sviluppo locale attivo e fornirà un link per visualizzare il report nel browser.

Il file di output può essere specificato utilizzando l'opzione di configurazione outputFile. Se non viene fornita alcuna opzione outputFile, verrà creato un nuovo file HTML.

bash
npx vitest --reporter=html
ts
export default defineConfig({
  test: {
    reporters: ['html'],
  },
});

TIP

Questo reporter richiede l'installazione del pacchetto @vitest/ui.

Reporter TAP ​

Produce un report conforme al Test Anything Protocol (TAP).

bash
npx vitest --reporter=tap
ts
export default defineConfig({
  test: {
    reporters: ['tap'],
  },
});

Esempio di un report TAP:

bash
TAP version 13
1..1
not ok 1 - __tests__/test-file-1.test.ts # time=14.00ms {
    1..1
    not ok 1 - first test file # time=13.00ms {
        1..2
        not ok 1 - 2 + 2 should equal 4 # time=11.00ms
            ---
            error:
                name: "AssertionError"
                message: "expected 5 to be 4 // Object.is equality"
            at: "/root-directory/__tests__/test-file-1.test.ts:20:28"
            actual: "5"
            expected: "4"
            ...
        ok 2 - 4 - 2 should equal 2 # time=1.00ms
    }
}

Reporter TAP Flat ​

Produce un report TAP flat. Come il reporter tap, i risultati dei test sono formattati per seguire gli standard TAP, ma le suite di test sono formattate come un elenco piatto anziché una gerarchia annidata.

bash
npx vitest --reporter=tap-flat
ts
export default defineConfig({
  test: {
    reporters: ['tap-flat'],
  },
});

Esempio di un report TAP flat:

bash
TAP version 13
1..2
not ok 1 - __tests__/test-file-1.test.ts > first test file > 2 + 2 should equal 4 # time=11.00ms
    ---
    error:
        name: "AssertionError"
        message: "expected 5 to be 4 // Object.is equality"
    at: "/root-directory/__tests__/test-file-1.test.ts:20:28"
    actual: "5"
    expected: "4"
    ...
ok 2 - __tests__/test-file-1.test.ts > first test file > 4 - 2 should equal 2 # time=0.00ms

Reporter Processi Bloccati ​

Visualizza un elenco di processi bloccati, se ve ne sono che impediscono a Vitest di terminare in sicurezza. Il reporter hanging-process non visualizza di per sé i risultati dei test, ma può essere utilizzato in combinazione con un altro reporter per monitorare i processi mentre i test sono in esecuzione. L'uso di questo reporter può essere intensivo in termini di risorse, pertanto dovrebbe essere generalmente riservato a scopi di debug in situazioni in cui Vitest non riesce costantemente a terminare il processo.

bash
npx vitest --reporter=hanging-process
ts
export default defineConfig({
  test: {
    reporters: ['hanging-process'],
  },
});

Reporter Github Actions ​

Produce comandi di workflow per fornire annotazioni per i fallimenti dei test. Questo reporter è abilitato automaticamente con un reporter default quando process.env.GITHUB_ACTIONS === 'true'.

Github ActionsGithub Actions

Se si configurano reporter non predefiniti, è necessario aggiungere esplicitamente github-actions.

ts
export default defineConfig({
  test: {
    reporters: process.env.GITHUB_ACTIONS ? ['dot', 'github-actions'] : ['dot'],
  },
});

È possibile personalizzare i percorsi dei file visualizzati nel formato del comando di annotazione di GitHub utilizzando l'opzione onWritePath. Questo è utile quando si esegue Vitest in un ambiente containerizzato, come Docker, dove i percorsi dei file potrebbero non corrispondere ai percorsi nell'ambiente GitHub Actions.

ts
export default defineConfig({
  test: {
    reporters: process.env.GITHUB_ACTIONS
      ? [
          'default',
          [
            'github-actions',
            {
              onWritePath(path) {
                return path.replace(
                  /^\/app\//,
                  `${process.env.GITHUB_WORKSPACE}/`
                );
              },
            },
          ],
        ]
      : ['default'],
  },
});

Reporter Blob ​

Salva i risultati dei test sulla macchina in modo che possano essere successivamente uniti utilizzando il comando --merge-reports. Per impostazione predefinita, memorizza tutti i risultati nella cartella .vitest-reports, ma può essere sovrascritto con i flag --outputFile o --outputFile.blob.

bash
npx vitest --reporter=blob --outputFile=reports/blob-1.json

Si consiglia di utilizzare questo reporter se si esegue Vitest su macchine diverse con il flag --shard. Tutti i report blob possono essere uniti in un unico report utilizzando il comando --merge-reports alla fine della pipeline CI:

bash
npx vitest --merge-reports=reports --reporter=json --reporter=default

TIP

Sia --reporter=blob che --merge-reports non funzionano in modalità watch.

Reporter Personalizzati ​

È possibile utilizzare reporter personalizzati di terze parti installati da NPM specificando il nome del pacchetto nell'opzione reporters:

bash
npx vitest --reporter=some-published-vitest-reporter
ts
export default defineConfig({
  test: {
    reporters: ['some-published-vitest-reporter'],
  },
});

Inoltre, è possibile definire i propri reporter personalizzati e utilizzarli specificando il percorso del file:

bash
npx vitest --reporter=./path/to/reporter.ts

I reporter personalizzati devono implementare l'interfaccia Reporter.

Pager
Pagina precedenteProgetti di Test
Pagina successivaCopertura

Rilasciato sotto la licenza MIT.

Copyright (c) 2021-Present Vitest Team

https://vitest.dev/guide/reporters

Rilasciato sotto la licenza MIT.

Copyright (c) 2021-Present Vitest Team