Installation and setup
It's time to take the first step forward Vitest Browser Mode! In this one, you and I are going to install all the necessary dependencies so we can start testing our components in the actual browser.
Install dependencies
As the first order of business, I'm going to uninstall the packages I won't be needing anymore:
npm uninstall jsdom @testing-library/react @testing-library/jest-dom
๐ฆ I am uninstalling React Testing Library because I won't be using it directly for my in-browser tests. That doesn't mean its API and practices are gone! Instead, I will continue using them through the Vitest and Playwright APIs that are inspired by RTL and promote its best practices.
Now I can install the dependencies required for the Browser Mode in Vitest:
npm i -D @vitest/browser vitest-browser-react
Let's break down what these packages do:
@vitest/browser
enables the browser mode and provides the bindings to interact with the underlying browser;vitest-browser-react
provisions rendering of React components (similar to@testing-library/react
);
The installation step is done, and now it's time to configure Vitest is it can run my component tests in the actual browser.
Configure Vitest
To enable the Browser Mode in Vitest, I need to set
test.browser.enabled
to true
in my vite.config.ts
/vitest.config.ts
:/// <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,
environment: 'jsdom',
browser: {
enabled: true,
},
},
})
As the next step, I need to tell Vitest what browsers I want for testing my components. Let's use Chromium by setting the
test.browser.instances
correctly:/// <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: {
browser: {
enabled: true,
instances: [
{
browser: 'chromium',
},
],
},
},
})
๐ฆ You can configure multiple browser instances to execute your component tests. This is handy for solid cross-browser code coverage. You will learn how to use browser providers later in this workshop.
Configure TypeScript
The last thing that remains is to extend the TypeScript configuration to recognize DOM-specific matches, like
expect().toBeVisible()
as they come built-in in Vitest.First, I will remove the
import '@testing-library/jest-dom/vitest'
import we previously had in the test:import '@testing-library/jest-dom/vitest'
And replace it with a type reference to Vitest's browser matchers in
tsconfig.test.json
:{
"extends": "./tsconfig.app.json",
"include": ["src/**/*", "src/**/*.test.ts*"],
"exclude": [],
"compilerOptions": {
"types": [
"vitest/globals",
// ๐
"@vitest/browser/matchers"
]
}
}
And with that, the installation step is done!