Mocha的“接口”系统使开发人员可以选择自己的DSL样式。Mocha具有BDD,TDD,Exports,QUnit和Require样式的接口。
BDD
的BDD接口提供describe(),context(),it(),specify(),before(),after(),beforeEach(),和afterEach()。context()只是的别名describe(),其行为方式相同;它只是提供一种使测试更易于阅读和组织的方法。同样,specify()是的别名it()。
所有先前的示例都是使用BDD接口编写的。
describe('Array', function() {before(function() {// ...});describe('#indexOf()', function() {context('when not present', function() {it('should not throw an error', function() {(function() {[1, 2, 3].indexOf(4);}.should.not.throw());});it('should return -1', function() {[1, 2, 3].indexOf(4).should.equal(-1);});});context('when present', function() {it('should return the index where the element first appears in the array', function() {[1, 2, 3].indexOf(3).should.equal(2);});});});});
TDD
的TDD接口提供suite(),test(),suiteSetup(),suiteTeardown(),setup(),和teardown():
$ mocha —ui tdd xxx.js
suite('Array', function() {setup(function() {// ...});suite('#indexOf()', function() {test('should return -1 when not present', function() {assert.equal(-1, [1, 2, 3].indexOf(4));});});});
require
该require界面允许您describe直接使用require和单词,并根据需要调用它们。如果要避免测试中使用全局变量,此接口也很有用。
注意:require接口不能通过node可执行文件运行,而必须通过来运行mocha。
var testCase = require('mocha').describe;var pre = require('mocha').before;var assertions = require('mocha').it;var assert = require('chai').assert;testCase('Array', function() {pre(function() {// ...});testCase('#indexOf()', function() {assertions('should return -1 when not present', function() {assert.equal([1, 2, 3].indexOf(4), -1);});});});
