前言
mocha及断言库chai的安装
安装在自己的项目上
yarn add mocha chai -D // 或 npm i --save-dev mocha chai |
最终:
"devDependencies": { "chai": "^4.2.0", "mocha": "^6.0.2" } |
babel7的安装
yarn add @babel/core @babel/cli @babel/preset-env @babel/register -D // 或 npm i --save-dev @babel/core @babel/cli @babel/preset-env @babel/register |
最终:
"devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.4.0", "@babel/preset-env": "^7.4.2", "@babel/register": "^7.4.0", "chai": "^4.2.0", "mocha": "^6.0.2" } |
增加babel.config.js文件
const presets = [ [ "@babel/env" ] ] module.exports = { presets } |
添加test命令脚本
"scripts": { "test": "./node_modules/.bin/mocha --require @babel/register test/*/*.spec.js" } |
1、其中的重点在于--require @babel/register这个命令,在目前找到的大多数教程中用的是
// babel7 --compilers js:@babel/register // babel7之前 --compilers js:babel-core/register |
但实际上--compilers这个方法已经被废弃了,具体可以查看wiki: compilers-deprecation
2、test/*/*.spec.js指向的是测试文件位置
实现测试方法
util目录下的date.js
/** * @description 闰年判断 * @date 2019-03-26 * @param {*} year * @returns {boolean} */ export function isLeapYear(year) { if (!year) return return year % 400 === 0 || (year % 4 === 0 && year % 100 !== 0) } /** * @description 获取该月有多少天 * @date 2019-03-26 * @param {(string | number)} date * @returns {number} */ export function getDaysOfMonth(date) { let d if (typeof date === "string" || typeof date === "number") { d = new Date(date) } else d = date const month = d.getMonth() + 1 const year = d.getFullYear() if (month === 2) return isLeapYear(year) ? 29 : 28 if ([1, 3, 5, 7, 8, 10, 12].includes(month)) return 31 else return 30 } |
test/unit/date.spec.js
import { isLeapYear, getDaysOfMonth } from '../../util/date' import { expect } from 'chai' describe('isLeapYear', () => { it('2020年是闰年', () => { expect(isLeapYear(2020)).to.be.true }) it('今年不是闰年', () => { expect(isLeapYear(2019)).to.be.false }) it('2000年是闰年', () => { expect(isLeapYear(2000)).to.be.true }) }) describe('getDaysOfMonth', () => { it('本月有31天', () => { expect(getDaysOfMonth(new Date())).to.equal(31) }) it('1月有31天', () => { expect(getDaysOfMonth('2019-01-12')).to.equal(31) }) it('2月有28天', () => { expect(getDaysOfMonth('2019-02-12')).to.equal(28) }) }) |
执行yarn test 或 npm run test,最终结果如下:
生成测试覆盖率报告
如果有需要的话我们也可以使用mochawesome生成一个代码覆盖率报告,其展示形式包括页面展示、json文件等
安装:
yarn add mochawesome -D // 或 npm install --save-dev mochawesome |
可以通过配置来指定报告生成的位置及文件名,具体操作为在test脚本命令中加入
// reportDir 指报告生成的文件夹 // reportFilename 报告名称 --reporter mochawesome --reporter-options reportDir=test/report,reportFilename=date // 最终的test脚本 "scripts": { "test": "./node_modules/.bin/mocha --require @babel/register test/*/*.spec.js --reporter mochawesome --reporter-options reportDir=test/report,reportFilename=date" } |
再次运行脚本可以看到
测试报告已经写入了指定位置
页面展示如下
工具
jsdoc-to-markdown (https://github.com/jsdoc2md/jsdoc-to-markdown)自动生成文档
jsdom-global(https://github.com/rstacruz/jsdom-global)通过在代码中添加DOM,您可以在node.js中对大部分客户端代码进行单元测试
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。