DEV Community

Pavel Belokon
Pavel Belokon

Posted on

Integrating Vitest

This week, I integrated some unit tests into my project with the help of Vitest. Vitest, in short, is a next-generation testing framework made natively for the native but can also be used separately from it.

Getting Started with Vitest

It is very simple to set up and running. For this example, I will be using npm.

Step one: installing, which can be done like this:
npm install -D vitest

Then, I set up a script for Vitest so that npm knows what to run for tests.

Go to your package.json and add the following for the test script:

{
  "scripts": {
    "test": "vitest"
  }
}
Enter fullscreen mode Exit fullscreen mode

A simple test can be written like this:

// sum.test.js
import { expect, test } from 'vitest'
import { sum } from './sum'

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3)
})
Enter fullscreen mode Exit fullscreen mode

Then simply run it with npm run test

One of the coolest things I learned about Vitest is that it has a smart & instant watch mode, which means it only reruns the related changes, just like HMR for tests. Also, if you open a specific file, it will only run tests for it, which is fantastic because you don't have to rerun all the tests, only in watch mode.

I conducted simple tests to check file-parsed text integrity and the existence of certain files. I don't think I uncovered anything new. I do believe that I can cover more edge cases, but I think I will work on that after I implement my code snippet feature since I want to finish parsing code first before I write tests for that.

I used Jest before, but since I have been using Vite and today, based on my lab's advice, I discovered Vitest and decided to use it.

Top comments (0)