先上源碼:demo
文件路徑:在項(xiàng)目根目錄/vue3/my-vue-app文件夾下
一嫌变、項(xiàng)目搭建
安裝vite和vue厅贪,使用 npm 或者 yarn、pnmp都行,終端命令如下:
# npm 6.x
npm create vite@latest my-vue-app --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest my-vue-app -- --template vue
# yarn
yarn create vite my-vue-app --template vue
# pnpm
pnpm create vite my-vue-app --template vue
二雪隧、Vitest、jsdom、 coverage安裝
使用 npm 或者 yarn、pnmp都行竞端,終端命令如下:
# npm
npm install -D vitest jsdom @vitest/coverage-c8
# yarn
yarn add -D vitest jsdom @vitest/coverage-c8
# pnpm
pnpm add -D vitest jsdom @vitest/coverage-c8
提示:Vitest 需要 Vite >=v3.0.0 和 Node >=v14
三、 修改項(xiàng)目根目錄下的vite.config.js的配置文件庙睡,增加:
test: { include: ["tests/*/.test.ts"], environment: "jsdom"}
完整內(nèi)容如下:
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
// 單元測試配置
test: {
include: ["tests/**/*.test.ts"],
environment: "jsdom"
}
})
四事富、修改package.json配置文件,增加:
"scripts": {"test": "vitest", "coverage": "vitest run --coverage"}
完整內(nèi)容如下:
{
"name": "my-vue-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"test": "vitest",
"coverage": "vitest run --coverage"
},
"dependencies": {
"vue": "^3.2.45"
},
"devDependencies": {
"@vitejs/plugin-vue": "^4.0.0",
"@vitest/coverage-c8": "^0.29.1",
"@vue/test-utils": "^2.3.0",
"jsdom": "^21.1.0",
"vite": "^4.1.0",
"vitest": "^0.29.1"
}
}
五埃撵、在項(xiàng)目根目錄下新建一個tests文件夾赵颅,然后在tests文件夾下新建一個單元測試文件demo.test.ts,完整內(nèi)容如下:
import { describe, expect, it } from 'vitest'
import { mount } from '@vue/test-utils'
// 需要測試的組件頁面
import Test from '@/pages/demo/test.vue'
const author1 = {
name: 'pany',
email: '939630029@qq.com',
url: 'https://github.com/pany-ang',
}
const author2 = {
name: 'pany',
email: '939630029@qq.com',
url: 'https://github.com/pany-ang',
}
describe('Test', () => {
it('測試基礎(chǔ)數(shù)據(jù)類型', () => {
expect(1 + 1).toBe(2)
})
it('測試引用類型', () => {
expect(author1).toEqual(author2)
})
it('組件正常渲染', () => {
const wrapper: any = mount(Test)
expect(wrapper.contains('div')).toBe(true)
})
})
參考資料: