- 安装mocha
npm init -y
npm i -D mocha
- 根目录创建add.js
function add(a, b) {
return a + b
}
module.exports = add;
- 创建test目录创建add.test.js
const add = require('../add');
const assert = require('assert');
describe('add', () => {
describe('add()', () => {
it('3+4 等于 7', () => {
assert.equal(add(3, 4), 7);
});
});
});
- node不支持import export 语法, 将node升级至v14.7.0
nvm ls #查看当前node版本
nvm install 14.7.0 #安装nodev.14.7.0
nvm use 14.7.0
- 更改add.js
export const add = (a, b) => {
return a + b
}
- 更改add.test.js
import {
add
} from "../add.js"
import assert from 'assert';
describe('add', () => {
describe('add()', () => {
it('3+4 等于 7', () => {
assert.equal(add(3, 4), 7);
});
});
});
- package.json
{
"name": "test-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^8.1.1"
},
"type": "module" //加入此关键
}
-
npm test 成功
安装nyc
npm i nyc
- package.json
{
"name": "test-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"coverage": "nyc mocha"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^8.1.1"
},
"type": "module",
"dependencies": {
"nyc": "^15.1.0"
}
}
- 创建.nycrc
{
"all": true,
"include": [
"src/*.mjs"
],
"exclude": [
"**/*.spec.js"
],
"nyc": {
"extension": [
".jsx",
".mjs"
]
}
}
创建src, 将add.js移入
-
npm run coverage
将js文件改为mjs后缀
-
npm run coverage
把mocha改为ava
npm i -D ava
- add.text.mjs
import {
add
} from "../src/add.mjs"
import test from 'ava';
// describe('add', () => {
// it('3+4 等于 7', () => {
// assert.equal(add(3, 4), 7);
// });
// });
test('add', t => {
if (add(3, 4) === 7) {
t.pass();
}
});
- package.json
{
"name": "test-demo",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "ava",
"coverage": "nyc ava"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@babel/core": "^7.11.4",
"@babel/preset-env": "^7.11.0",
"ava": "^3.11.1",
"babel-loader": "^8.1.0",
"mocha": "^8.1.1"
},
"type": "module",
"dependencies": {
"nyc": "^15.1.0",
"webpack": "^4.44.1"
}
}
-
npm run coverage