---
title: Vitest
description: Learn how to integrate Allure with Vitest to generate rich, interactive test reports. Follow step-by-step setup, test execution, and report generation guidance.
---

# Getting started with Allure Vitest

[![Allure Vitest npm latest version](https://img.shields.io/npm/v/allure-vitest?style=flat "Allure Vitest npm latest version")](https://www.npmjs.com/package/allure-vitest)

Generate beautiful HTML reports using [Allure Report](https://allurereport.org/docs/) and your [Vitest](https://vitest.dev/) tests.

Info:
Check out the example projects at [github.com/allure-examples](https://github.com/orgs/allure-examples/repositories?q=visibility%3Apublic+archived%3Afalse+topic%3Aexample+topic%3Avitest) to see Allure Vitest in action.

## Setting up

### 1. Prepare your project

1. Make sure [Node.js](https://nodejs.org/) is installed.

   Allure Vitest is tested against Node.js 18 and higher. Older versions may work, but we can't guarantee that.

1. Open a terminal and go to the project directory. For example:

   ```bash
   cd /home/user/myproject
   ```

1. Make sure Allure Report is installed. If it's not, follow the [installation instructions](/docs/v2/install/). Note that Allure Report requires Java.

1. Install the Allure Vitest integration and make sure that all the packages it needs are installed.

   **npm:**
   ```bash
   npm install --save-dev vitest @vitest/runner allure-vitest
   ```

   **yarn:**
   ```bash
   yarn add --dev vitest @vitest/runner allure-vitest allure-js-commons
   ```

   **pnpm:**
   ```bash
   pnpm install --dev vitest @vitest/runner allure-vitest
   ```

   Warning:
   If you run the tests and see the “no vitest context is detected” error, make sure the `vitest` and `@vitest/runner` packages are both listed as your project's `devDependencies` and have the same version.

   If you plan to run tests in a real browser using [Vitest Browser Mode](https://vitest.dev/guide/browser/), also install `@vitest/browser` and a browser provider. Allure Vitest supports the Playwright provider:

   **npm:**
   ```bash
   npm install --save-dev @vitest/browser @vitest/browser-playwright playwright
   npx playwright install chromium
   ```

   **yarn:**
   ```bash
   yarn add --dev @vitest/browser @vitest/browser-playwright playwright
   yarn playwright install chromium
   ```

   **pnpm:**
   ```bash
   pnpm install --dev @vitest/browser @vitest/browser-playwright playwright
   pnpm playwright install chromium
   ```

1. Modify your [Vitest configuration file](https://vitest.dev/config/), e.g., `vitest.config.ts`.

   - In the list of setup files, add `"allure-vitest/setup"` (for most package managers) or `require.resolve("allure-vitest/setup")` (for Yarn PnP).

   - In the list of reporters, add `"allure-vitest/reporter"`.

   - Optionally, specify `resultsDir` and other options for the reporter. See [Allure Vitest configuration](/docs/vitest-configuration/) for more details.

   **Normal configuration:**
   ```ts
   import AllureReporter from "allure-vitest/reporter";
   import { defineConfig } from "vitest/config";

   export default defineConfig({
     test: {
       setupFiles: ["allure-vitest/setup"],
       reporters: [
         "verbose",
         [
           "allure-vitest/reporter",
           {
             resultsDir: "allure-results",
           },
         ],
       ],
     },
   });
   ```

   **Configuration for Yarn PnP:**
   ```ts
   import AllureReporter from "allure-vitest/reporter";
   import { defineConfig } from "vitest/config";

   const require = createRequire(import.meta.url);

   export default defineConfig({
     test: {
       setupFiles: [require.resolve("allure-vitest/setup")],
       reporters: [
         "verbose",
         [
           "allure-vitest/reporter",
           {
             resultsDir: "allure-results",
           },
         ],
       ],
     },
   });
   ```

### 2. Run tests

Run your Vitest tests same way as your would run them usually. For example:

**npm:**
```bash
npm test
```

**yarn:**
```bash
yarn test
```

**pnpm:**
```bash
pnpm test
```

This will save necessary data into `allure-results` or other directory, according to the [configuration](/docs/vitest-configuration/). If the directory already exists, the new files will be added to the existing ones, so that a future report will be based on them all.

### 3. Generate a report

Finally, convert the test results into an HTML report. This can be done by one of two commands:

- `allure generate` processes the test results and saves an HTML report into the `allure-report` directory. To view the report, use the `allure open` command.

- `allure serve` creates the same report as `allure generate`, then automatically opens the main page of the report in a web browser.

## Writing tests

The Allure Vitest integration extends the standard reporting features of Vitest by providing additional capabilities for crafting more informative and structured tests. This section highlights key enhancements that can be utilized:

- **Metadata Annotation**: Enhance test reports with [descriptions, links, and other metadata](#add-metadata).
- **Test Organization**: Structure your tests into clear hierarchies for better readability and organization [organize tests](#organize-tests).
- **Step Division**: Break down tests into smaller [test steps](#divide-a-test-into-steps) for easier understanding and maintenance.
- **Parametrized Tests**: Clearly describe the parameters for [parametrized tests](#describe-parametrized-tests) to specify different scenarios.
- **Set labels globally**: Use [environment variables](#set-labels-globally) to set metadata and other labels.
- **Attachments**: Automatically capture [screenshots and other files](#attach-screenshots-and-other-files) during test execution.
- **Test Selection**: Use a test plan file to [select which tests to run](#select-tests-via-a-test-plan-file), allowing for flexible test execution.
- **Environment Details**: Include comprehensive [environment information](#environment-information) to accompany the test report.

In most cases, Allure Vitest provides two different ways to use a feature: the Runtime API and the Metadata API.

- **Runtime API**: use Allure's functions to add certain data to the test result during its execution. This approach allows for constructing the data dynamically.

  Note that it is recommended to call the Allure's functions as close to the beginning of the test as possible. This way, the data will be added even if the test fails early.

- **Metadata API**: add a metadata tag (beginning with `@`) into the test name. Allure Vitest will extract it and update the test result's data accordingly. When using this approach, the data is guaranteed to be added regardless of how the test itself runs.

### Add Metadata

Allure allows you to enrich your reports with a variety of [metadata](/docs/v2/readability/#description-links-and-other-metadata). This additional information provides context and details for each test, enhancing the report's usefulness. Refer to the [metadata reference section](/docs/vitest-reference/#metadata) for an exhaustive list of what can be added.

**Runtime API:**
```ts
import * as allure from "allure-js-commons";
import { test } from "vitest";

test("Test Authentication", async () => {
  await allure.displayName("Test Authentication");
  await allure.owner("John Doe");
  await allure.tags("Web interface", "Authentication");
  await allure.severity("critical");
  // ...
});
```

**Metadata API:**
```ts
import { test } from "vitest";

test(
  "Test Authentication" +
    " @allure.label.owner:JohnDoe" +
    " @allure.label.tag:WebInterface" +
    " @allure.label.tag:Authentication" +
    " @allure.label.severity:critical",
  async () => {
    // ...
  },
);
```

### Organize tests

As described in [Improving navigation in your test report](/docs/v2/navigation/), Allure supports multiple ways to organize tests into hierarchical structures.

To specify a test's location in the [behavior-based hierarchy](/docs/v2/navigation/#behavior-based-hierarchy):

**Runtime API:**
```ts
import * as allure from "allure-js-commons";
import { test } from "vitest";

test("Test Authentication", async () => {
  await allure.epic("Web interface");
  await allure.feature("Essential features");
  await allure.story("Authentication");
  // ...
});
```

**Metadata API:**
```ts
import { test } from "vitest";

test(
  "Test Authentication" +
    " @allure.label.epic:WebInterface" +
    " @allure.label.feature:EssentialFeatures" +
    " @allure.label.story:Authentication",
  async () => {
    // ...
  },
);
```

To specify a test's location in the [suite-based hierarchy](/docs/v2/navigation/#suite-based-hierarchy):

**Runtime API:**
```ts
import * as allure from "allure-js-commons";
import { test } from "vitest";

test("Test Authentication", async () => {
  await allure.parentSuite("Tests for web interface");
  await allure.suite("Tests for essential features");
  await allure.subSuite("Tests for authentication");
  // ...
});
```

**Metadata API:**
```ts
import { test } from "vitest";

test(
  "Test Authentication" +
    " @allure.label.parentSuite:TestsForWebInterface" +
    " @allure.label.suite:TestsForEssentialFeatures" +
    " @allure.label.subSuite:TestsForAuthentication",
  async () => {
    // ...
  },
);
```

### Divide a test into steps

To [create steps and sub-steps](/docs/steps/), you can use the `step()` function, see the [reference](/docs/vitest-reference/#test-steps).

```ts
import * as allure from "allure-js-commons";
import { Status } from "allure-js-commons";
import { test } from "vitest";

test("Test Authentication", async () => {
  await allure.step("Step 1", async () => {
    await allure.step("Sub-step 1", async (ctx) => {
      await ctx.parameter("foo", "1");
      // ...
    });
    await allure.step("Sub-step 2", async (ctx) => {
      await ctx.parameter("foo", "2");
      // ...
    });
  });
  await allure.logStep("Step 2", Status.SKIPPED);
});
```

### Describe parametrized tests

Since tests in Vitest, unlike in some other frameworks, are written as anonymous functions, it is very easy to implement the [parametrized tests](/docs/v2/readability/#parametrized-tests) pattern, i.e. to run the same test logic with different test data. To do so, just write the test inside a loop and use the variable parameters in both its title and its body.

To display a parameter value in the test report, pass it to the [`parameter()`](/docs/vitest-reference/#parametrized-tests) function.

**Using test():**
```ts
import * as allure from "allure-js-commons";
import { test } from "vitest";

for (const login of ["johndoe", "johndoe@example.com"]) {
  test(`Test Authentication as ${login}`, async () => {
    await allure.parameter("login", login);
    await allure.parameter("time", new Date().toUTCString(), { excluded: true });
    // ...
  });
}
```

**Using test.each():**
```ts
import * as allure from "allure-js-commons";
import { test } from "vitest";

test.each(["johndoe", "johndoe@example.com"])("Test Authentication as %s", async (login) => {
  await allure.parameter("login", login);
  await allure.parameter("time", new Date().toUTCString(), { excluded: true });
  // ...
});
```

### Set labels globally

Any [labels](/docs/vitest-reference/#label), including custom ones, can be set via the environment variables in your operating system. Here's an example (assuming you use the `npm` package manager):

**MacOS/Linux:**
```bash
export ALLURE_LABEL_epic=WebInterface
npm test
```

**Windows:**
```powershell
$Env:ALLURE_LABEL_epic = "WebInterface"
npm test
```

### Attach screenshots and other files

In Allure reports, you have the ability to [attach various types of files](/docs/attachments/), which can greatly enhance the comprehensibility of the report. A common practice is to attach screenshots that capture the state of the user interface at specific moments during test execution.

For detailed instructions on how to implement attachments, refer to the [attachments section in the Allure Vitest reference](/docs/vitest-reference/#attachments).

```ts
import * as allure from "allure-js-commons";
import { ContentType } from "allure-js-commons";
import { test } from "vitest";

test("Test Authentication", async () => {
  // ...

  await allure.attachment("Text file", "This is the file content.", ContentType.TEXT);

  await allure.attachmentPath("Screenshot", "/path/to/image.png", {
    contentType: ContentType.PNG,
    fileExtension: "png",
  });
});
```

### Select tests via a test plan file

If the `ALLURE_TESTPLAN_PATH` environment variable is defined and points to an existing file, Vitest will only run tests listed in this file.

Here's an example of running tests according to a file named `testplan.json` (assuming you use the `npm` package manager):

**MacOS/Linux:**
```bash
export ALLURE_TESTPLAN_PATH=testplan.json
npm test
```

**Windows:**
```powershell
$Env:ALLURE_TESTPLAN_PATH = "testplan.json"
npm test
```

### Environment information

For the main page of the report, you can collect various information about the environment in which the tests were executed. To do so, edit the [`environmentInfo`](/docs/vitest-configuration/#environmentinfo) object in the configuration.

For example, it is a good idea to use this to remember the OS version and Node.js version retrieved from the [`os`](https://nodejs.org/api/os.html) and [`process`](https://nodejs.org/api/process.html) objects. This may help the future reader investigate bugs that are reproducible only in some environments.

Images: /images/js/environment-allure3.png, /images/js/environment-allure2.png

```ts
import { createRequire } from "node:module";
import * as os from "node:os";
import { defineConfig } from "vitest/config";

const require = createRequire(import.meta.url);

export default defineConfig({
  test: {
    setupFiles: [require.resolve("allure-vitest/setup")],
    reporters: [
      "verbose",
      [
        "allure-vitest/reporter",
        {
          environmentInfo: {
            os_platform: os.platform(),
            os_release: os.release(),
            os_version: os.version(),
            node_version: process.version,
          },
        },
      ],
    ],
  },
});
```

Note that if your launch includes multiple Vitest runs (see [How it works](/docs/how-it-works/)), Allure Vitest will only save the environment information from the latest run.

## Using Browser Mode

[Vitest Browser Mode](https://vitest.dev/guide/browser/) runs your tests inside a real browser instead of a simulated DOM environment.

Info:
Browser Mode support requires Vitest 4 or later.

To enable Browser Mode, add a `browser` block to your Vitest configuration. In Vitest 4, the browser provider is imported as a factory from its own package:

```ts
import { playwright } from "@vitest/browser-playwright";
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    setupFiles: ["allure-vitest/browser/setup"],
    reporters: [
      "verbose",
      [
        "allure-vitest/reporter",
        {
          resultsDir: "allure-results",
        },
      ],
    ],
    browser: {
      enabled: true,
      provider: playwright(),
      instances: [{ browser: "chromium" }],
    },
  },
});
```

Warning:
`allure-vitest/browser/setup` is not interchangeable with `allure-vitest/setup`. The browser setup file is designed to run in a browser context and registers additional commands required for test plan filtering. If your project has both unit tests and browser tests, use a separate Vitest config file for each, pointing to the appropriate setup file.

All standard Allure Vitest features — metadata, steps, attachments, and so on — work the same way in Browser Mode. In addition, you can capture screenshots of the browser page and attach them to the test result using the `page` object from `vitest/browser`:

```ts
import * as allure from "allure-js-commons";
import { ContentType } from "allure-js-commons";
import { test } from "vitest";
import { page } from "vitest/browser";

test("Renders the login form", async () => {
  // ... render and interact with the page ...

  const screenshotPath = await page.screenshot();
  await allure.attachmentPath("Page screenshot", screenshotPath, {
    contentType: ContentType.PNG,
    fileExtension: "png",
  });
});
```

For more details on attaching screenshots and other files, see the [attachments section in the Allure Vitest reference](/docs/vitest-reference/#attachments).
