Using Vitest for unit testing

JavaScript unit testing with Vitest

Since we use Vite to develop our projects, a good choice for unit testing is to use the Vitest package. Using Vitest will simplify the setup needed to be able to perform unit testing. In addition, the syntax for doing the unit testing with Vitest is similar to Jest. Since Jest is a popular choice for unit test software for JavaScript, learning to use Vitest will be helpful if you need to use Jest in the future.

What unit tests are about

Unit tests are tests designed to test if the program you are developing is working correctly. If you are working on a programming project for a team, it is highly likely that some form of unit testing will be used to ensure the code works correctly. A team project will be broken up into sections. This is so a team member or members will be responsible for a section, and the programming tasks can be spread out among the team.

If such a project is set up correctly, each section will have a set of unit tests that must all pass before any changes can be committed. So, different team members are often working in branches for the overall program. Only if all the unit tests for all the sections pass, should code in a branch be merged into the main branch. So, if you are working on a section of the software, you must run all the unit tests for your section and every other section. This is to ensure that changes you make, don’t break code in any of the sections. It would be very difficult to make progress on a project, if someone else’s code makes it so that the code you were working on no longer works correctly.

Such a system is only as good as the unit tests. If the unit tests don’t check every feature, then you might not know when something has gone wrong. Also, the unit tests must be done correctly, or you or someone else can be fooled into thinking that the code they are working on does not have errors. So, it should be easy to see that using unit testing, as well as designing the unit tests are an important skill as a programmer.

Basic setup to use Vitest

Setup on StackBlitz

  • Start a new project using the JS Vanilla template.

  • Run npm install -D vitest jsdom in the Terminal

  • Modify package.json to include the following:

"scripts": {
  "test": "vitest run"
}
  • Create the file vitest.config.js with the following contents:

vitest.config.js
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    environment: 'jsdom',
    globals: true,
  },
})

The package.json file should be set to this:

package.json
{
  "name": "vitest-student-adder",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "vitest run --reporter=verbose",
    "test:watch": "vitest"
  },
  "devDependencies": {
    "vitest": "latest",
    "jsdom": "latest",
    "vite": "latest"
  }
}