Starter with React + TypeScript + Vitest

Installing Vitest and React Testing Library in a Vite project

Install dependencies

yarn add -D vitest @vitest/ui eslint-plugin-vitest
yarn add -D jsdom @testing-library/jest-dom@6.0.0 @testing-library/dom @testing-library/react @testing-library/user-event
yarn add -D @types/jest
yarn add -D @vitest/coverage-v8
  • Newer version >= v16 of React Testing Library may require @testing-library/dom
  • @testing-library/dom is required for the screen object in React Testing Library
  • @testing-library/user-event is required for the userEvent for simulating user events
  • @testing-library/jest-dom v6.0.0 is required for compatibility with @types/jest and Vitest, as the latest version may not fully support the current TypeScript configuration and potentially causing some documentation methods to be unavailable

Add test scripts to package.json test object

{
  "test": "vitest",
  "test:ui": "vitest --ui",
  "test:verbose": "vitest --run --reporter verbose",
  "test:coverage": "vitest --coverage"
}

Update TypeScript configuration tsconfig.json

// In tsconfig.json
"compilerOptions": {
...
"types": ["vitest/globals", "@testing-library/jest-dom"]
},
"include": [
...
"./vitest.setup.ts"
],

Add Vitest plugin to ESLint

import vitest from 'eslint-plugin-vitest'

export default tseslint.config(
    {
        languageOptions: {
            globals: {
                ...vitest.environments.env.globals
            }
        },
        plugins: {
            vitest
        },
        rules: {
            ...vitest.configs.recommended.rules, // you can also use vitest.configs.all.rules to enable all rules
            'no-unused-vars': 'warn', // warning, not error
            'vitest/expect-expect': 'off', // eliminate distracting red squiggles while writing tests
            'react/prop-types': 'off' // turn off props validation
        }
    }
)

Update vite configuration for tests

Update vitest.config.js. Add this property / value to the defineConfig argument:

import {defineConfig, mergeConfig} from 'vitest/config'
import {UserConfig} from 'vitest/node';
import viteConfig from './vite.config';

export default mergeConfig(viteConfig as UserConfig, defineConfig({
    test: {
        globals: true,
        environment: 'jsdom',
        reporters: ['verbose'],
        pool: 'forks',
        setupFiles: ['./vitest.setup.ts']
    }
}));

Add setup file for jest-dom

// In your own vitest.setup.ts (or any other name)
import '@testing-library/jest-dom/vitest';