package.json
{
"name": "mocha-test",
"version": "1.0.0",
"description": "Mocha simple test",
"main": "hello.js",
"scripts": {
"test": "mocha"
},
"keywords": [
"mocha",
"test"
],
"author": "Michael Liao",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/michaelliao/learn-javascript.git"
},
"dependencies": {},
"devDependencies": {
"mocha": "3.0.2"
}
}
hello.js
module.exports = function (...rest) {
var sum = 0;
for (let n of rest) {
sum += n;
}
return sum;
};
test
hello-test.js
const assert = require('assert');
const sum = require('../hello');
describe('#hello.js', () => {
describe('#sum()', () => {
it('sum() should return 0', () => {
assert.strictEqual(sum(), 0);
});
it('sum(1) should return 1', () => {
assert.strictEqual(sum(1), 1);
});
it('sum(1,2) should return 3', () => {
assert.strictEqual(sum(1, 2), 3);
});
it('sum(1,2,3) should return 6', () => {
assert.strictEqual(sum(1, 2, 3), 6);
});
});
})
在package.json中添加npm命令:
{
...
"scripts": {
"test": "mocha"
},
...
}
在hello-test目录下执行命令
C:\...\hello-test> npm test
before和after
hello-test.js
const assert = require('assert');
const sum = require('../hello');
describe('#hello.js', () => {
describe('#sum()', () => {
before(function () {
console.log('before:');
});
after(function () {
console.log('after.');
});
beforeEach(function () {
console.log(' beforeEach:');
});
afterEach(function () {
console.log(' afterEach.');
});
it('sum() should return 0', () => {
assert.strictEqual(sum(), 0);
});
it('sum(1) should return 1', () => {
assert.strictEqual(sum(1), 1);
});
it('sum(1, 2) should return 3', () => {
assert.strictEqual(sum(1, 2), 3);
});
it('sum(1, 2, 3) should return 6', () => {
assert.strictEqual(sum(1, 2, 3), 6);
});
});
});