一、安装插件
npm i @testing-library/vue jsdom vitest -D
二、在package.json中配置scripts命令脚本
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test": "vitest"
},
三、创建一个.vue组件和.test.js/ts文件
.vue组件
<script setup lang='ts' >
import { ref } from "vue"
let add = ref(0)
function handleAdd() {
add.value++
}
</script>
<template>
{{ add }}
<button @click="handleAdd">add++</button>
</template>
<style scoped></style>
.test.js/ts
import { fireEvent, render } from "@testing-library/vue";
import { describe, test } from "vitest";
import Counter from "./App.vue"
describe("组件测试", () => {
test("组件一", async () => {
const { getByText } = render(Counter)
getByText("0")
const button = getByText('add++')
await fireEvent.click(button)
getByText("1")
await fireEvent.click(button)
getByText("2")
})
})
四、如果是ts项目,则需要在ts.config.js的compilerOptions节点中配置
"types": [
"vitest/globals"
],
五、需要在vite.config.js中配置
/// <reference types="vitest" />
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
test: {
globals: true,
environment: "jsdom"
},
plugins: [vue()],
})