mocha默認加載test目錄下的test.js,也能夠經過參數指定須要運行的測試文件,如運行test目錄下的test.math.js。html
mocha test/test.math.js
mocha的測試腳本node
describe('test of math', function () { it('should return 2 when 1 + 1', function () { assert.equal(math.add(1, 1), 2); }); });
上面使用的是nodejs的assert斷言庫,也能夠安裝其餘斷言庫,如npm
mocha容許在test目錄下經過mocha.opts文件,進行參數配置。
mocha.optsasync
--timeout 5000 --reporter mochawesome
控制檯顯示的測試結果:測試
test of math ✓ should return 2 when 1 + 1 ✓ use expect assertion: should return 2 when 1 + 1 ✓ asyncAdd, should return 2 when 1 + 1 (2004ms) - a pending test 3 passing (2s) 1 pending
--reporter參數能夠配置使用的測試報表名稱,如spec, dot, nyan, mochawesomeui
mochawesome須要安裝this
npm install --save-dev mochawesome
報表生成在mochawesome-report目錄下,爲html文件。code
Istanbulhtm
npm install --save-dev nyc
在mocha命令前增長nycip
nyc mocha test/test.math.js
運行改命令後:
----------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ----------|----------|----------|----------|----------|-------------------| All files | 100 | 100 | 100 | 100 | | math.js | 100 | 100 | 100 | 100 | | ----------|----------|----------|----------|----------|-------------------|
如須要生成代碼覆蓋率的報告,能夠修改命令爲:
nyc --reporter=html mocha test/test.math.js
運行命令後,覆蓋率報表會生成在coverage目錄下。
var assert = require('assert'); var expect = require('expect.js'); var Math = require('../math'); var math; describe('test of math', function () { //hooks before(function () { // runs before all tests in this block math = new Math(); }); after(function () { // runs after all tests in this block }); beforeEach(function () { // runs before each test in this block }); afterEach(function () { // runs after each test in this block }); it('should return 2 when 1 + 1', function () { assert.equal(math.add(1, 1), 2); }); it('should return 1 when 1 * 1', function () { assert.equal(math.mutiply(1, 1), 1); }); it('should return max value 9 of [1,3,6,9,0]', function () { assert.equal(math.max([1, 3, 6, 9, 0]), 9); }); it('should return 2 when 1 + 1', function () { assert.equal(math.add(1, 1), 2); }); it('use expect assertion: should return 2 when 1 + 1', function () { expect(math.add(1, 1)).to.be(2); }); it('asyncAdd, should return 2 when 1 + 1', function (done) { math.asyncAdd(1, 1).then(function (result) { assert.equal(result, 2); done(); }, function (err) { assert.fail(err); done(); }); }); it('a pending test'); });