Skip to main content

Vitest 測試指南

1. 安裝必要套件**

基本上需要這些:

pnpm add -D vitest @vue/test-utils vue

如果用的是 Vue 3(建議):

pnpm add -D @vue/test-utils@next

搭配測試環境模擬 DOM(建議加)

pnpm add -D jsdom

因為 vitest 會用 jsdom 模擬瀏覽器環境來讓 Vue 組件可以正常渲染。

2. 設定 Vitest

在 vitest.config.ts:

import { defineConfig } from "vitest/config";
import vue from "@vitejs/plugin-vue";

export default defineConfig({
plugins: [vue()],
test: {
environment: "jsdom",
globals: true,
coverage: {
provider: "c8",
reporter: ["text", "html"],
},
},
});

⚠️ 注意 environment: 'jsdom',不然 Vue 渲染會失敗。

3. 寫一個 Vue 組件測試範例

假設有一個

HelloWorld.vue

<template>
<div>
<h1>{{ msg }}</h1>
<button @click="count++">Clicked {{ count }} times</button>
</div>
</template>

<script setup>
import { ref } from 'vue'

const props = defineProps({ msg: String })
const count = ref(0)
</script>

測試檔

HelloWorld.spec.ts

import { describe, it, expect } from "vitest";
import { mount } from "@vue/test-utils";
import HelloWorld from "./HelloWorld.vue";

describe("HelloWorld.vue", () => {
it("renders props.msg properly", () => {
const wrapper = mount(HelloWorld, { props: { msg: "Hello Vitest" } });
expect(wrapper.text()).toContain("Hello Vitest");
});

it("increments count on click", async () => {
const wrapper = mount(HelloWorld, { props: { msg: "Test" } });
await wrapper.find("button").trigger("click");
expect(wrapper.text()).toContain("Clicked 1 times");
});
});

4. 執行測試

pnpm vitest run

或 watch 模式:

pnpm vitest

5. 執行 coverage(剛剛你問的)

pnpm vitest run --coverage

6. 小提醒

  • 對 .vue 檔案測試,建議用 @vue/test-utils 的 mount(),比單純 import 還穩定。
  • 可用 mock 方式測試外部 API、Pinia、Router、i18n 等。