摩卡作为图书馆

Eri*_*ord 7 javascript mocha.js node.js coffeescript

我想使用mocha(node.js测试框架,而不是ruby模拟库)作为库,而不是使用mocha可执行文件来运行我的测试.

有可能以这种方式运行摩卡测试吗?这些例子都只是调用mocha库假设它们已经"require'd",并且mocha可执行文件提前完成所有"需要",但我真的更喜欢在我的脚本中明确地执行它们以便我可以简单地在我的脚本上设置+ x并直接调用它.

我可以这样做吗?

#!/usr/bin/env coffee
mocha = require 'mocha'
test = mocha.Test
suite = mocha.Suite
assert = require("chai").assert

thing = null

suite "Logging", () ->
  setup (done) ->
    thing = new Thing()
    done()
  test "the thing does a thing.", (done) ->
    thing.doThing () ->
      assert.equal thing.numThingsDone, 1
      done()
  teardown (done) ->
    thing = null
    done()
Run Code Online (Sandbox Code Playgroud)

Eri*_*ord 2

此功能已被添加。我在下面举了一个例子。

我从这里得到信息

您将需要 2 个文件。一项测试,一项运行测试。您可以将 runTest 标记为可执行文件,并在 mocha 选项中设置其输出。

运行测试.js

#!/usr/bin/env node

var Mocha = require('mocha'),
    fs    = require('fs'),
    path  = require('path');

var mocha = new Mocha(
{
  ui: 'tdd'     
});

mocha.addFile(
  path.join(__dirname, 'test.js')
);

mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});
Run Code Online (Sandbox Code Playgroud)

测试.js

var assert = require('chai').assert

suite('Array', function(){
  setup(function(){});
  suite('#indexOf()', function(){
    test('should return -1 when not present', function(){
      assert.equal(-1, [1,2,3].indexOf(4));
    });
  });
});
Run Code Online (Sandbox Code Playgroud)