How to set up Vitest for Node.js testing

Learn how to easily setup Vitest.

4 min read

views

Requirements

  • Node.js installed with v18 or higher
  • Basic Node.js app

What is Vitest?

Vitest is a fast and simple testing framework for Node.js, React, Next.js, Vue, Svelte, etc. It's built on top of Vite, which is a fast build tool for JavaScript and TypeScript. Vitest is also compatible with Jest, which is another popular testing framework.

Installation

Firstly, we will install Vitest as a development dependency:

npm install --save-dev vitest
bash

Configuring the project

To run tests with Vitest, we need to add a script to our package.json. We will call it test:

{
  "name": "my-nodejs-app",
  "version": "0.0.0",
  "scripts": {
    "test": "vitest"
  }
}
json

Adding a test file

Now that we have added the test script, we can start adding test files. Vitest will by default search for files ending with .test.js or .test.ts. Let's create a file called math.test.ts in the src folder:

maths.test.ts
import { expect, test } from "vitest";
 
test("Math.sqrt()", () => {
  expect(Math.sqrt(4)).toBe(2);
  expect(Math.sqrt(144)).toBe(12);
  expect(Math.sqrt(2)).toBe(Math.SQRT2);
});
ts

If you're not familiar with the test and expect functions, they allow use write assertions and tests. In simple terms:

  • test: Run a test with a name and a function.
  • expect: Make sure that the value is equal to the expected value.

Running the tests

To run these tests, simply run the test command we created earlier:

npm run test
bash

This will show all passed and failed tests.

Tip: You can also view the test results in the browser by adding the --ui flag to the test command:

{
  "scripts": {
    "test": "vitest",
    "test:ui": "vitest --ui"
  }
}
json

More from Vitest

You can use Vitest for many more project types, such as: React, Next.js, Vue, Svelte, etc. Read more about the awesomeness Vitest can do on their documentation

Personally, I use Vitest in many of my projects and I absolutely love it! It's simple to set up, fast and has a great community.

Online Example