前端也要搞测试 ~ vue + vitest
关于 JavaScript 的测试,听到比较多的有 jest,但各知名博主强烈推荐 vitest,于是我也来玩玩 vitest……
vitest VS jest
- vitest 比 jest 快,更多各种 powerful😳
- 支持 vue,reactJS 等火热前端框架
- jest 支持的各种 API,vitest 也可以🤪
——博主们的推荐理由
安装 vitest
以 vue3 为例,安装 vitest 之前需要有 vue 项目……
npm install -g @vue/cli vue create <project-name>
项目创建好后,即可安装 vitest
npm install -D vitest
vitest 可以使用 jsdom 和 happy-dom,这里以 happy-dom 安装为例
npm install @vitejs/plugin-vue @vue/test-utils happy-dom -D
安装完需要的各种包,可以在 package.json 文件下看到刚刚的安装成果。还可以在 package.json 里添加 vitest script
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "vitest",
"coverage": "vitest run --coverage"
},
在 script 栏,添加 test 和 coverage 脚本……
创建 vitest.config.js
在项目文件夹下创建 vitest.config.js
import { defineConfig } from "vitest/config"
import vue from "@vitejs/plugin-vue"
export default defineConfig({
plugins: [vue()],
test: {
globals: true,
environment: "happy-dom",
},
root: ".", // define the root
})
环境配置完成后,可以测试了……
以 HelloWorld 为例,component 里有 HelloWorld.vue, 代码如下:
<template>
<p> </p>
</template>
<script>
export default {
name: "HelloWorld",
props: {
message: {
type: String,
default: "World",
},
},
setup(props) {
return {
msg: props.message,
}
}
}
</script>
<style>
</style>
测试 HelloWorld Component
在项目文件下创建 tests 文件夹,用于存放各种测试代码……
在创建的 tests 文件夹下创建 HelloWorld.test.js —— 测试文件命名规则:<component name>.test.js
import { mount } from "@vue/test-utils"
import HelloWorld from "../src/components/HelloWorld.vue"
import { describe, it, expect } from "vitest"
describe("HelloWorld.vue", () => {
it("should renders is page content is correct", () => {
const message = "Happy People"
const testMessage = "Happy People"
const wrapper = mount(HelloWorld, {
props: { message }
})
expect(wrapper.text()).toBe(testMessage)
})
it("should render if props value is correct", () => {
const message = "Happy People"
const testMessage = "Happy People"
const wrapper = mount(HelloWorld, {
props: { message }
})
expect(wrapper.vm.message).toBe(testMessage)
})
})
看看测试效果如何……
npx vitest tests/HelloWorld.test.js

HelloWorld 测试文件中有两个测试案例。没有问题的话,就都通过了……
……
……
继续往 tests 文件夹创建一一对应的测试文件。
创建各种测试案例,什么 edge case 之类的……
……
……
想要一次跑所有的测试文件,可以借用刚刚在 package.json 创建的 vitest 脚本
npm run test
使用 coverage 则可以生成报告 😅
npm run coverage

这时项目文件夹下还会多出 coerage 的文件夹,即测试报告的网页版……

网页版当然可以在浏览器里查看详情……非常先进……🤪
参考文献:
https://www.thisdot.co/blog/getting-started-with-vue-and-vitest