How to Test Vite + React application (Vitest)

November 15, 2023

Vitest

Jest can be used in vite project, but it is not fully supported. Vitest is a test runner for vite project.

Install

yarn add -D vitest @testing-library/react jest-dom

Configuration

// vite.config.js
 import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';
import eslint from 'vite-plugin-eslint';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.jsx',
            ssr: 'resources/js/ssr.jsx',
            refresh: true
        }),
        react(),
        eslint({
            include: ['/resources/js/**/*.jsx', '/public/assets/*'],
            exclude: ['node_modules/**']
        })
    ],
+   test: {
+       globals: true,
+       files: ['resources/js/**/*.test.js'],
+       environment: 'jsdom'
+   },
    resolve: {
        alias: {
            '@hoil': '/resources/js',
            '@assets': '/public/assets'
        },
        extensions: ['.js', '.jsx', '.ts', '.tsx']
    },
    ssr: {
        noExternal: ['@inertiajs/react', '@inertiajs/react/server']
    }
});

Usage

yarn vitest

Reference



Profile picture

Written by Yerin Hong who lives in London and works in the UK.