Shared assets

There are two types of test setup you can have: global and local. The global setup applies to all tests, while the local one can be introduced on a test suite or a test case basis. I would like to include some shared assets, like styles, to apply to all component tests, which means I need a global setup.
I will start by creating a vitest.browser.setup.ts file. The naming here doesn't matter that much, but I like to keep Vitest-related files starting with vitest.*.
In that file, I will import the assets I want to include when rendering any component:
import './src/index.css'
To make Vite process this file the same way it does the rest of my application, I need to include a type reference to vite-env.d.ts:
/// <reference path="./src/vite-env.d.ts" />
import './src/index.css'
Since we added this new file, we have to tell TypeScript how it should be handled. In tsconfig.test.json, add vitest.browser.setup.ts to the compilerOptions.include array:
{
	"extends": "./tsconfig.app.json",
	"include": [
		// The setup file runs in the browser just like the test suite.
		"vitest.browser.setup.ts",
		"src/**/*",
		"src/**/*.test.ts*"
	],
	"exclude": [],
	"compilerOptions": {
		"types": ["vitest/globals", "@vitest/browser/providers/playwright"]
	}
}
Now all that remains is to tell Vitest to use this file as the global setup for the Browser Mode.
In vite.config.ts, I will provide the path to this setup file as the value for the setupFiles property on the current browser instance:
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'

export default defineConfig({
	plugins: [react(), tailwindcss()],
	test: {
		globals: true,
		browser: {
			enabled: true,
			provider: 'playwright',
			instances: [
				{
					browser: 'chromium',
					setupFiles: ['./vitest.browser.setup.ts'],
				},
			],
		},
	},
})
If I run my tests now, I will see that the styles are applied to the rendered component correctly! ๐ŸŽ‰
A screenshot of the Vitest UI showing the file preview component with the styles applied

Please set the playground first

Loading "Shared assets"
Loading "Shared assets"
Login to get access to the exclusive discord channel.