vite + vue3 的项目中使用 vitest 做单元测试(仅供参考)

一、配置文件

// vitest.config.ts

import { fileURLToPath } from 'node:url'
import { mergeConfig, defineConfig } from 'vite'
import { configDefaults } from 'vitest/config'
// import viteConfig from './vite.config'


import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'


export default mergeConfig(
  defineConfig({
    // 安装了tsx插件才需配置
    plugins: [
      vue(),
      vueJsx(),
    ],
  }),
  defineConfig({
    test: {
      globals: true,
      // 测试环境,模拟浏览器环境的库jsdom
      environment: 'jsdom',
      // 测试覆盖工具
      coverage: {
        provider: "c8"
      },
      // 测试报告
      reporters: ['junit'],
      // 测试报告生成文件
      outputFile: './coverage/junit.xml',
      exclude: [...configDefaults.exclude, 'e2e/*'],
      root: fileURLToPath(new URL('./', import.meta.url)),
      transformMode: {
        web: [/\.[jt]sx$/]
      }
    }
  })
)

二、全量覆盖率报告

在 vitest 中 集成了c8,c8 是测试覆盖率检查的工具,告诉开发者代码中有哪些代码行被覆盖了,哪些没有覆盖。

在package.json增加npm script

"test:coverage": "vitest --coverage"

如果没安装c8,运行命令的话,Vitest 会提示安装 c8,默认yes,回车执行安装。安装后,命令行删除测试覆盖率,同时在 src/coverage 下生成一个测试报告。

三、测试报告

在package.json增加npm script

"test:unit": "vitest --watch=false --coverage --reporter=junit",

四、关闭热更新

配置一个命令行参数–watch==false 就可以关闭这种行为

"test:unit": "vitest --watch=false --coverage"

五、编写测试用例

打开 vscode 新建一个 components 目录并新增一个button目录,然后再建一个__test__目录放测试文件,elemetn-plus 源码也是这样做的,在里面新建一个xxx.test.ts 或者 tsx 的文件(没安装tsx就建ts文件)。

vitest默认会检测项目中所有.test.ts或者.test.tsx等之类的测试文件,这个是可以修改的,具体配置可以参考官网去改。

// HelloWorld.spec.ts

import { describe, it, expect } from 'vitest'


import { mount } from '@vue/test-utils'
import HelloWorld from '../HelloWorld.vue'

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

<script setup lang="ts">
defineProps<{
  msg: string
}>()
</script>

<template>
  <div class="greetings">
    <h1 class="green">{
   
   { msg }}</h1>
    <h3>
      You’ve successfully created a project with
      <a href="https://vitejs.dev/" target="_blank" rel="noopener">Vite</a> +
      <a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3</a>. What's next?
    </h3>
  </div>
</template>

<style scoped>
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  position: relative;
  top: -10px;
}

h3 {
  font-size: 1.2rem;
}

.greetings h1,
.greetings h3 {
  text-align: center;
}

@media (min-width: 1024px) {
  .greetings h1,
  .greetings h3 {
    text-align: left;
  }
}
</style>

参考

Vitest | 由 Vite 提供支持的极速单元测试框架

Vite | 下一代的前端工具链

Vitest: 现代前端测试框架 - 知乎

猜你喜欢

转载自blog.csdn.net/qq_31851435/article/details/132908162
今日推荐