乐闻世界logo
搜索文章和话题

How to write unit test for components with vitest in Nuxt 3?

1个答案

1

1. Initialize Vitest

Before starting unit tests with Vitest in a Nuxt 3 project, ensure Vitest is installed. Add Vitest-related dependencies by modifying the project's package.json file.

json
"devDependencies": { "vitest": "^0.5.0", "vue-test-utils": "^2.0.0-rc.15" }

Then run:

bash
npm install

2. Configure Vitest

Create a vitest.config.ts file in the project root to configure Vitest. We configure the test environment as jsdom since we are testing Vue components.

typescript
import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' export default defineConfig({ plugins: [vue()], test: { globals: true, environment: 'jsdom' } })

3. Write Test Cases

Assume we have a simple Vue component MyButton.vue with a button that emits a custom event when clicked.

vue
<template> <button @click="handleClick">{{ label }}</button> </template> <script setup> defineProps({ label: String }) function handleClick() { emit('clicked') } </script>

Create a test file MyButton.test.js.

javascript
import { describe, it, expect } from 'vitest' import { mount } from '@vue/test-utils' import MyButton from './MyButton.vue' describe('MyButton', () => { it('should emit "clicked" event when button is clicked', async () => { const wrapper = mount(MyButton, { props: { label: 'Click Me' } }) await wrapper.find('button').trigger('click') expect(wrapper.emitted()).toHaveProperty('clicked') }) })

4. Run Tests

To run tests, add a script to package.json to launch Vitest.

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

Run tests:

bash
npm run test

5. Analyze Test Results

After executing the above command, Vitest will run all matching test files and output results in the command line. Ensure all tests pass to confirm the component functions as expected.

Summary

Using Vitest for component testing in a Nuxt 3 project is a straightforward process. By correctly configuring, writing test cases, running, and analyzing tests, you can effectively ensure the functionality and stability of Vue components.

2024年7月31日 00:39 回复

你的答案