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.
First, install Vitest and the Vue plugin for Vite:
npm install -D vitest @vitejs/plugin-vue vite-tsconfig-paths
pnpm add vitest @vitejs/plugin-vue vite-tsconfig-paths --save-dev
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]
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
tsconfig.json
Open the tsconfig.json
file and add @vitest/globals
to the "types"
section:
{
"compilerOptions": {
"types": ["vitest/globals"]
}
}
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)
})
})
package.json
Update your package.json
to include a test script:
{
"scripts": {
"test": "vitest"
}
}
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.
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! 🚀