- // 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">Vitea> +
- <a href="https://vuejs.org/" target="_blank" rel="noopener">Vue 3a>. 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>