I hope this post can help you get set up with Vitest, I had issues getting the software to work with Vue test utils, specifically because of bad configuration. I hope this guide can help you learn and set up quickly with Vitest to start building your software. Let’s get started.

Sidenote: Vitest is a testing framework compatible with Jest and runs on Vite a fast development tooling framework to make your life easier.

Installing

To install Vitest, you should be using a node package manager, such as NPM or Yarn. I will use yarn because it’s quick to install libraries and get going. In your terminal and within your project. Run this line:

yarn add -D vitest

Great! Vitest should be installed! That was quick.

Set up your configuration file correctly

You may encounter an issue that exclaims: ‘Document not defined.’ This is probably due to several things, but we should first verify the configuration file. If you are using Vitest, you may likely be using Vite. So with that assumption, this solution will fix this error in this context.

Open vite.config.ts and add the following to your defineConfig({})

export default defineConfig({
test: {
    globals: true,
    environment: 'jsdom',
    include: ['./src/lib/**/*.spec.ts'],
  }
... // build code listed here
})

Now you should be able to start creating unit tests just fine. Let’s try with a dummy test file called: math.spec.ts

// math.ts
export function multiply(firstNum: number, secondNum: number): number {
return firstNum * secondNum;
}
//math.spec.ts
import {test, expect} from 'vitest';
import {multiply} from 'math.ts';

test('multiplies 2 * 2 to equal 4', () => {
  expect(multiply(2, 2)).toBe(4)
})

If everything is working, you’ll be able to see your unit tests running just fine. To expand this further, let’s try a test with Vue:

import { mount } from '@vue/test-utils'
import {test, expect} from 'vitest';

// Your component to test
const DashboardComponent = {
  template: '<p>{{ msg }}</p>',
  props: ['msg']
}

test('displays dashboard greeting', () => {
  const wrapper = mount(DashboardComponent, {
    props: {
      msg: 'Greetings'
    }
  })

  // Assert the rendered text of the component
  expect(wrapper.text()).toContain('Greetings')
})

We’re Done

That’s that, I hope this helped. It was tricky for me when I first started with Vitest, but hopefully, I’ve simplified the process for you all. If you have any questions feel free to leave a comment.