原文地址:Testing Vue components with Vitest
现代前端开发需要强大的测试实践,以确保应用程序的可靠性和可维护性。
值得庆幸的是,在 Vue 中我们可以使用一个由 Vite 提供支持的神奇工具 - Vitest,它可以让我们轻松测试 Vue 组件。
在本文中,我将深入探讨如何使用 Vitest 来测试 Vue 组件。
什么是Vitest
Vitest是一个速度极快的测试框架,旨在与现代构建工具 Vite 无缝协作。这就是为什么 Vitest 是测试 Vue 组件的绝佳选择:
- 速度:Vitest 基于 Vite构建,利用其快速的构建时间和热更新(HMR);
- TypeScript 支持:Vitest 具有开箱即用的TypeScript支持;
- Vue集成:它与Vue Test Utils (Vue的官方测试库)配合良好;
- 丰富的功能:Vitest包括快照测试、模拟和监视模式等功能,可简化开发。
使用Vitest测试Vue组件
首先,确保您有一个使用Vite设置的Vue项目。然后,安装Vitest及相关库
pnpm install --save-dev vitest @vue/test-utils vue
添加 vitest.config.ts
文件来配置 Vitest
import vue from '@vitejs/plugin-vue'
import { defineConfig } from 'vitest/config'
export default defineConfig({
plugins: [vue()], // 测试vue项目需要引入vue驱动
test: {
globals: true,
environment: 'jsdom', // 使用浏览器模式测试
// setupFiles: './vitest.setup.ts', // 需要全局变量时启用
}
})
如果需要执行全局配置(如模拟全局变量),请创建 vitest.setup.ts
文件
import matchers from '@testing-library/jest-dom/matchers';
import { expect } from 'vitest';
expect.extend(matchers);
让我们为Vue组件编写一个简单的测试。创建 HelloWorld.vue
组件
<script setup lang="ts">
import { ref } from 'vue';
const message = ref('Hello, Vue!')
function updateMessage() {
message.value = 'You clicked the button!'
}
</script>
<template>
<div>
<h1>{{ message }}</h1>
<button @click="updateMessage">
Click Me
</button>
</div>
</template>
在 tests
目录中创建 HelloWorld.spec.ts
文件:
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import HelloWorld from '../src/components/HelloWorld.vue';
describe('HelloWorld.vue', () => {
it('renders the correct message', () => {
const wrapper = mount(HelloWorld);
expect(wrapper.text()).toContain('Hello, Vue!');
});
it('updates the message when the button is clicked', async () => {
const wrapper = mount(HelloWorld);
await wrapper.find('button').trigger('click');
expect(wrapper.text()).toContain('You clicked the button!');
});
});
使用以下命令运行测试:
npx vitest
为了获得更具互动性的体验,您可以使用watch来监听文件改动:
npx vitest --watch
译者注
vitest 会自动监听文件变化,原文中的此处内容可忽略
你也可以在 package.json
中添加一行命令,使用 pnpm run test
来运行测试
{
"scripts": {
"test": "vitest",
},
}
奖励:额外的测试技术
快照测试捕获渲染组件的输出并将其与基线进行比较。将快照测试添加到 HelloWorld.spec.ts
:
译者注
文件也可以是 HelloWorld.test.ts
,此时vitest也可以找到测试文件
it('matches the snapshot', () => {
const wrapper = mount(HelloWorld);
expect(wrapper.html()).toMatchSnapshot();
});
Vitest 允许您模拟模块和函数。例如:
vi.mock('axios', () => ({
default: {
get: vi.fn(() => Promise.resolve({ data: 'Mocked Data' }))
}
}));
测试组件如何处理 props 和发出事件:
it('renders with props', () => {
const wrapper = mount(HelloWorld, {
props: { initialMessage: 'Hello, Props!' }
});
expect(wrapper.text()).toContain('Hello, Props!');
});
译者注
这时,你可以改动HelloWorld.vue组件来观察测试结果
<script setup lang="ts">
import { ref } from "vue"
const props = defineProps<{
initialMessage: string
}>()
</script>
<template>
<div>
<h1>{{ initialMessage }}</h1>
</div>
</template>
import { mount } from '@vue/test-utils';
import { describe, expect, it, vi } from 'vitest';
import NewHelloWorld from '../src/components/NewHelloWorld.vue';
describe('NewHelloWorld.vue', () => {
it('renders with props', () => {
const wrapper = mount(NewHelloWorld, {
props: { initialMessage: 'Hello, Props!' }
});
expect(wrapper.text()).toContain('Hello, Props!');
});
});
原文之外的扩展【译者注】
@vitest/ui
Vitest 由 Vite 提供能力,在运行测试时有一个开发服务器。这允许 Vitest 提供一个漂亮的 UI 界面来查看并与测试交互。Vitest 的 UI 界面是可选的,你可以通过以下安装:
npm i -D @vitest/ui
接下来,你可以通过传入 --ui 参数来启动测试的 UI 界面:
vitest --ui
vitest in vscode
当然您也可以安装vitest 扩展在vscode中点击侧边栏进行测试,且测试结果会以icon形式展示
总结
使用 Vitest 测试 Vue 组件是一个简单且令人愉快的过程。它的速度、现代功能和无缝 Vue 集成使其成为希望确保其应用程序健壮且可维护的开发人员的绝佳选择。
保重,下次再见!
And happy coding as always 🖥️
评论区
评论加载中...