LazyCodet

a

17:32:11 22/2/2025 - 1 views -
Programming

Setting Up and Using Vitest in Nuxt 3 to write unit tests

Vitest is a powerful and lightweight testing framework optimized for Vite. In this guide, we’ll walk through how to set up Vitest in a Nuxt 3 project to write and run unit tests effectively.

Installing Vitest

First, install Vitest and the Vue plugin for Vite:

  • ​npm:
npm install -D vitest @vitejs/plugin-vue vite-tsconfig-paths
  • pnpm​
pnpm add vitest @vitejs/plugin-vue vite-tsconfig-paths --save-dev

Configuring Vitest

Create a new file named vitest.config.ts in the root of your project and add the following content:

import { defineConfig } from 'vitest/config'
import Vue from '@vitejs/plugin-vue'
import tsconfigPaths from 'vite-tsconfig-paths';

export default defineConfig({
    plugins: [Vue(), tsconfigPaths()],
    test: {
        globals: true,
        setupFiles: [resolve(__dirname, 'vitest.setup.ts')]
    }
});

The tsconfigPaths plugin can help you solve the problem that paths are defined in vite.config.ts [1]

Setup vitest.setup.ts

Create a file named ​vitest.setup.ts:

import { JSDOM } from 'jsdom';

const dom = new JSDOM('<!doctype html><html><body></body></html>', {
    url: 'http://localhost'
});

(global as any).window = dom.window;
global.document = dom.window.document;

// If there are more DOM related globals you need, you can add them like this:
global.Node = window.Node;
global.Element = window.Element;

​This file can help you can interact with DOM

Updating tsconfig.json

Open the tsconfig.json file and add @vitest/globals to the "types" section:

{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

Creating a Test Directory and Writing the First Test

Create a new folder named tests, then create a test file inside it, for example: tests/example.test.ts. Add the following test case:

import { describe, test, expect } from 'vitest'

describe('Basic Math', () => {
  test('Addition', () => {
    const result = 1 + 1
    expect(result).toEqual(2)
  })
})

Adding a Test Script in package.json

Update your package.json to include a test script:

{
  "scripts": {
    "test": "vitest"
  }
}

Running the Tests

Now, you can run the test using the following command:

npm run test

If everything is set up correctly, you should see a success message in your terminal indicating that the test passed.


Conclusion

Vitest is an excellent testing tool for Nuxt 3, making unit testing easy and efficient. With this setup, you can write and run tests seamlessly to ensure your application works as expected.


Does this guide cover everything you need? Let me know if you'd like any modifications or additions! 🚀

References

[_] - ​https://www.youtube.com/watch?v=dhKuM-StUhM

​[1] - https://stackoverflow.com/a/77815473/21614343