Vue项目覆盖率展示

本文介绍了如何在Vue项目中设置单元测试,包括创建测试、调整文件位置、使用mochawesome输出测试报告以及通过nyc和karma扫描测试覆盖率。详细步骤从创建Vue CLI项目开始,涵盖测试编写、配置文件修改以及生成的测试报告和覆盖率报告的查看。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

建立一个集成了单元测试的Vue项目

  1. 创建一个vue-cli项目
  vue create mytestdemo
  
  # 选择手动配置
  Please pick a preset: 
    	zcloud (router, vuex, less, babel, eslint, unit-jest) 
  	    default (babel, eslint) 
  	  * Manually select features 
  	  
  	  
  	  
 # 选择需要的功能
? Please pick a preset: Manually select features
? Check the features needed for your project: 
		 ◉ Babel
		 ◯ TypeScript
		 ◯ Progressive Web App (PWA) Support
		 ◉ Router
		 ◉ Vuex
		 ◉ CSS Pre-processors
		 ◉ Linter / Formatter
		 ◉ Unit Testing
		❯◉ E2E Testing

# 使用 history 模式
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) (Y/n) Y


# scss
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): 
  Sass/SCSS (with dart-sass) 
❯ Sass/SCSS (with node-sass) 
  Less 
  Stylus  
  
  
  
  # esLint
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: 
  ESLint with error prevention only 
  ESLint + Airbnb config 
❯ ESLint + Standard config 
  ESLint + Prettier 
  
  
  
  
  # 保存时进行检测
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)
❯◉ Lint on save
 ◯ Lint and fix on commit
 
 
 
 
 # 单元测试 mocha + chai
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)Lint on save
? Pick a unit testing solution: (Use arrow keys)
❯ Mocha + Chai 
  Jest 
  
  
  
   # 端到端测试
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)Lint on save
? Pick a unit testing solution: Mocha
? Pick a E2E testing solution: (Use arrow keys)
❯ Cypress (Chrome only) 
  Nightwatch (WebDriver-based) 


# 单独的配置文件
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)Lint on save
? Pick a unit testing solution: Mocha
? Pick a E2E testing solution: Cypress
? Where do you prefer placing config for Babel, ESLint, etc.? 
❯ In dedicated config files 
  In package.json 


# 不保存配置
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex, CSS Pre-processors, Linter, Unit, E2E
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: Standard
? Pick additional lint features: (Press <space> to select, <a> to toggle all, <i> to invert selection)Lint on save
? Pick a unit testing solution: Mocha
? Pick a E2E testing solution: Cypress
? Where do you prefer placing config for Babel, ESLint, etc.? In dedicated config files
? Save this as a preset for future projects? (y/N) n


# 开始创建项目
Vue CLI v4.1.2
✨  Creating project in /Users/heyi/File/Front-End/demo/vue-unit.
🗃  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...

···

📄  Generating README.md...

🎉  Successfully created project vue-cli4-unit-mocha-chai-nyc.
👉  Get started with the following commands:

 $ cd vue-cli4-unit-mocha-chai-nyc
 $ npm run serve

创建项目完成后,可以发现 cli4 会自动生成一个默认的单元测试例子 tests/unit/ example.spec.js,其内容如下:
import {
    expect } from 'chai'
import {
    shallowMount } from '@vue/test-utils'
import HelloWorld from '@/components/HelloWorld.vue'

describe('HelloWorld.vue', () => {
   
  it('renders props.msg when passed', () => {
   
    const msg = 'new message'
    const wrapper = shallowMount(HelloWorld, {
   
      propsData: {
    msg }
    })
    expect(wrapper.text()).to.include(msg)
  })
})
接下来,进入项目并运行单元测试:
cd mytestdemo
npm run test:unit

> vue-cli4-unit-mocha-chai-nyc@0.1.0 test:unit /Users/heyi/File/Front-End/demo/_unit/vue-cli4-unit-mocha-chai-nyc
> vue-cli-service test:unit

WEBPACK  Compiling...

  [===                      ] 10% (building)Download the Vue Devtools extension for a better development experience:
https://github.com/vuejs/vue-devtools
You are running Vue in development mode.
Make sure to turn on production mode when deploying for production.
See more tips at https://vuejs.org/guide/deployment.html
  [=========================] 98% (after emitting)

 DONE  Compiled successfully in 3019ms

  [=========================] 100% (completed)

 WEBPACK  Compiled successfully in 3019ms

 MOCHA  Testing...



  HelloWorld.vue
    ✓ renders props.msg when passed


  1 passing (26ms)

 MOCHA  Tests completed successfully

npm run test:unit 命令会自动读取 tests/unit/ 目录下的 *.spec.js 文件,来跑我们的单元测试。

手写单元测试

首先我们在 src/components/ 目录下创建文件 AppEmpty.vue,其内容如下:

<template>
  <div>{
  {text}}</div>
</template>

<script>
export default {
  name: 'AppEmpty',
  props: {
    text: {
      type: String,
      default: 'no data'
    }
  },
  data () {
    return {}
  }
}
</script>

<style scoped lang="scss">
</style>

接着在 tests/unit/ 目录下创建 app-empty.spec.js 文件,并添加如下内容:

import {
    expect } from 'chai'
import {
    shallowMount } from '@vue/test-utils'
import AppEmpty from '@/components/AppEmpty.vue'

describe('AppEmpty.vue', () => {
   
  it('no props.text when passed', () => {
   
    const wrapper = shallowMount(AppEmpty)
    expect(wrapper.text()).to.include('no data')
  })

  it('renders props.text when passed', (
### 提高 Vue2 项目中 Jest 单元测试覆盖率的方法 #### 配置 `jest.config.js` 文件中的选项 为了提高单元测试覆盖率,合理配置 jest 的配置文件至关重要。通过设置 `collectCoverageFrom` 可以指定哪些文件需要被覆盖测试[^3]。 ```javascript module.exports = { collectCoverageFrom: ['src/**/*.{js,vue}', '!src/**/*.spec.{js,vue}'], }; ``` 此配置会收集来自 `src/` 目录下的所有 `.js` 和 `.vue` 文件的代码覆盖率数据,但排除了所有的测试文件(`*.spec.*`)。 #### 使用合适的断言库和工具 对于异步函数或组件生命周期钩子等复杂逻辑部分,可以利用诸如 `@testing-library/vue` 或者 `vue-test-utils` 这样的辅助库来进行更全面深入地模拟与验证操作行为[^1]。 例如,在编写针对带有定时器功能的方法时: ```javascript import { shallowMount } from '@vue/test-utils'; import flushPromises from 'flush-promises'; // 处理Promise链路延迟执行的问题 // ...其他导入语句... describe('Demo.vue', () => { it('should call callback after timeout when calling TimeoutFn()', async () => { const wrapper = shallowMount(Demo); let result; await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); Demo.TimeoutFn((msg) => {result = msg}); }); expect(result).toBe("hello Timeout"); }); // 更多测试... }); ``` 这段代码展示了如何处理异步调用并确保它们按预期工作。 #### 设定合理的覆盖率阈值 在 `package.json` 中定义最低可接受的覆盖率标准有助于团队成员了解期望的质量水平,并促使大家努力达成目标。 ```json { "jest": { "coverageThreshold": { "global": { "statements": 80, "branches": 75, "functions": 80, "lines": 80 } } } } ``` 这将强制要求整个项目的陈述、分支、函数以及行级别的覆盖率至少分别为80%、75%、80% 和 80%,如果未能满足这些条件,则构建过程可能会失败或者显示警告信息。 #### 编写详尽而有效的测试案例 尽可能多地考虑边界情况和其他可能发生的场景可以帮助增加代码路径的数量从而提升整体覆盖率。比如上面提到的例子中不仅包含了正常流程还应该加入异常情形下的响应方式。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值