Hello React Vitest

React, Vitest & TypeScript

Configure Vitest in React projects

4 min read

In this chapter we'll install and configure Vitest, a Unit Test Framework very similar to Jest: it's faster, smart and powered by Vite:.

Install Vitest:

npm install -D vitest

Add following script to package.json:

scripts: {
  // ...
  "test": "vitest",

Now you can create your first (useless) test.

Create a new file: src/components/Hello.test.ts:

import React from 'react';

test('render text', () => {

and run your test suite:

npm run test

You'll get following errors

ReferenceError: test is not defined

You can fix it by simpling adding the global option to vite.config.ts:

/// <reference types="vitest" />
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import checker from 'vite-plugin-checker';

// https://vitejs.dev/config/
export default defineConfig({
  test: {
   globals: true, // < ==
  plugins: [
    checker({ typescript: true }),
    // You can also disable type checking when running testing with Vitest
    // !process.env.VITEST ? checker({ typescript: true }) : undefined,

what is ///?

We have also used /// < reference types="vitest" / >.

Triple-slash references instruct the compiler to include additional files in the compilation process. In fact you'll get some TypeScript errors, if you remove it (see image below).

More info on TypeScript Documentation

Now you should kill the current process ( CTRL + C ) and run tests again: npm run test.

It should works now:

Your editor (I use WebStorm) may still display some errors, on test and expect commands:

I highly recommend to add vitest types in tsconfig.json:

  "compilerOptions": {
    "types": ["vitest/globals"],
    // ...

Command Line

You can also run your tests directly from command line too:

npx vitest

or you can also filter and run some specific tests :

✅ vitest Hello       # run the `Hello.test.tsx` (watch mode)
❌ vitest foo         # no tests with this name. Errors
✅ vitest run Hello   # run the `Hello.test.tsx` (NO watch)

In the next chapter we'll configure React Testing Library and we write a test for a React component.

Keep updated about latest content
videos, articles, tips and news