Rules Hub
Coding Rules Library
Configure mixed test environments using Vitest projects
Use the projects configuration in Vitest to isolate Node-based unit tests from browser-based integration tests in a single file.
Bad example
| 1 | import { defineConfig } from "vitest/config"; |
| 2 |
|
| 3 | export default defineConfig({, |
| 4 | test: { |
| 5 | // forcing all tests to run in jsdom or node creates issues |
| 6 | environment: "jsdom", |
| 7 | include: ["src/**/*.test.{ts,tsx}"], |
| 8 | setupFiles: ["./setup.ts"], |
| 9 | }, |
| 10 | }); |
Explanation (EN)
Using a single environment for all tests forces compromises. Logic tests run slower in 'jsdom', while browser tests might fail or require excessive mocking if forced into 'node'. It treats all tests as the same type.
Objašnjenje (HR)
Korištenje jednog okruženja za sve testove prisiljava na kompromise. Logički testovi se izvode sporije u 'jsdom', dok testovi preglednika mogu pasti ili zahtijevati pretjerano mockanje ako su prisiljeni u 'node'. Tretira sve testove kao istu vrstu.
Good example
| 1 | import { defineConfig } from "vitest/config"; |
| 2 | import { playwright } from "@vitest/browser-playwright"; |
| 3 |
|
| 4 | export default defineConfig({ |
| 5 | test: { |
| 6 | // Shared config can go here or inside projects |
| 7 | projects: [ |
| 8 | { |
| 9 | name: "unit", |
| 10 | environment: "node", |
| 11 | include: ["tests/unit/**/*.test.ts"], |
| 12 | }, |
| 13 | { |
| 14 | name: "browser", |
| 15 | test: { |
| 16 | include: ["tests/browser/**/*.test.tsx"], |
| 17 | browser: { |
| 18 | enabled: true, |
| 19 | provider: playwright({ launchOptions: { headless: true } }), |
| 20 | instances: [{ browser: "chromium" }], |
| 21 | }, |
| 22 | }, |
| 23 | }, |
| 24 | ], |
| 25 | }, |
| 26 | }); |
Explanation (EN)
Using `projects` allows distinct configurations for unit and browser tests within the same file. Unit tests remain fast in Node, while integration tests get a real browser environment via Playwright.
Objašnjenje (HR)
Korištenje `projects` omogućuje zasebne konfiguracije za jedinične testove i testove preglednika unutar iste datoteke. Jedinični testovi ostaju brzi u Nodeu, dok integracijski testovi dobivaju stvarno okruženje preglednika putem Playwrighta.