较便宜的网站建设,抓取工具把对手网站的长尾词,中国企业信息公示网登录官网,开发小网站一般多少钱一个Vitest 是个高性能的前端单元测试框架,它的用法其实和 Jest 差不多,但是它的性能要优于 Jest 不少,还提供了很好的 ESM 支持,同时对于使用 vite 作为构建工具的项目来说有一个好处就是可以公用同一个配置文件vite.config.js。因此本项目将会使用 Vitest 作为测试框架。
安装
…Vitest 是个高性能的前端单元测试框架,它的用法其实和 Jest 差不多,但是它的性能要优于 Jest 不少,还提供了很好的 ESM 支持,同时对于使用 vite 作为构建工具的项目来说有一个好处就是可以公用同一个配置文件vite.config.js。因此本项目将会使用 Vitest 作为测试框架。
安装
因为我们测试的前端组件库是运行在浏览器上的,所以我们需要额外安装happy-dom,同时我们还需要安装展示测试覆盖率工具c8
pnpm add vitest happy-dom c8 -D -w配置
上面提到过,Vitest 的配置可以直接在vite.config.ts中配置,所以我们来到components/vite.config.ts中对 Vitest 做一个相关配置(三斜线命令告诉编译器在编译过程中要引入的额外的文件)
/// reference typesvitest /
import { defineConfig } from vite;
import vue from vitejs/plugin-vue
...
export default defineConfig({...test: {environment: happy-dom},}
)
然后我们在package.json中增加两个命令vitest和vitest run --coverage,分别是进行单元测试和查看单元测试覆盖情况 scripts: {test: vitest,coverage: vitest run --coverage}此时我们便可以使用 Vitest 进行测试了,在执行test命令时,Vitest 会执行**/.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}的文件,这里我们的测试文件统一命名为**/.{test}.ts的形式并放在每个组件的__tests__目录下 比如在 button 目录下新建__tests__/button.test.ts目录,然后写一个简单的测试代码看一下效果如何
import { describe, expect, it } from vitest;describe(helloeasyest, () {it(should be helloeasyest, () {expect(hello easyest).toBe(helloeasyest);});
});然后在components目录下执行pnpm run test就可以看到我们的测试通过了 然后执行pnpm run coverage可以看到我们测试覆盖情况 其中它们每个字段代表的含义如下 %stmts 是语句覆盖率statement coverage是不是每个语句都执行了 %Branch 分支覆盖率branch coverage是不是每个 if 代码块都执行了 %Funcs 函数覆盖率function coverage是不是每个函数都调用了 %Lines 行覆盖率line coverage是不是每一行都执行了
如何测试组件?
上面我们只是简单测试了一个字符串相加,但是我们需要测试的是组件库,那么如何测试我们的组件是否复合要求呢? 因为我们项目是 vue 组件库,因此我们可以安装 Vue 推荐的测试库vue/test-utils
pnpm add vue/test-utils -D -w然后我们修改一下button.test.ts,我们来测试一下 Button 组件的 slot
import { describe, expect, it } from vitest;import { mount } from vue/test-utils;
import button from ../button.vue;
// The component to test
describe(test button, () {it(should render slot, () {const wrapper mount(button, {slots: {default: easyest}});// Assert the rendered text of the componentexpect(wrapper.text()).toContain(easyest);});
});vue/test-utils提供了一个mount方法,我们可以传入不同参数来测试组件是否复合我们的预期,比如上面测试代码的含义是:传入 button 组件,并将其默认 slot 设置为easyest,我们期望页面加载的时候文本会展示easyest,很显然我们的 button 组件是有这个功能的,所以我们执行pnpm run test的时候这条测试就通过了 如果我们想测试 Button 组件传入 type 展示某个样式的时候可以这样写
import { describe, expect, it } from vitest;import { mount } from vue/test-utils;
import button from ../button.vue;
// The component to test
describe(test button, () {it(should render slot, () {const wrapper mount(button, {slots: {default: easyest}});// Assert the rendered text of the componentexpect(wrapper.text()).toContain(easyest);});it(should have class, () {const wrapper mount(button, {props: {type: primary}});expect(wrapper.classes()).toContain(ea-button--primary);});
});这条测试的含义是:当我们传入的type为primary的时候,期望组件的类名为ea-button–primary,很显然这条也是可以通过的,同时这时候你会发现我们刚刚启动的测试自己自动更新了,说明Vitest是具有热更新功能的 关于vue/test-utils更多功能感兴趣的可以点击vue/test-utils查看官方文档