摩卡作为一个图书馆

我想使用mocha(node.jstesting框架,而不是ruby mocking库)作为库,而不是使用mocha可执行文件来运行我的testing。

这样可以进行摩卡testing吗? 这些例子都假设它们已经是“需要”的,就叫做mocha库,而mocha可执行文件提前完成所有的“require-ing”,但是我真的希望在脚本中明确地做到这一点,这样我就可以简单地在我的脚本上设置+ 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() 

这是可能的,但肯定不推荐。

看看摩卡二进制的来源(特别是bin/_mocha )来了解它的function。 尤其要看runfunction 。 它所使用的一切 – RunnerReporter等等 – 都是由摩卡库导出的,所以没有任何东西阻止你对其进行逆向工程。

此function已被添加。 我在下面包含一个例子。

我从这里得到的信息:

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

runTest.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); }); }); 

test.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)); }); }); }); 

以下片段允许您以编程方式控制节点外的Mocha主要function,如在不同步骤中添加套件和运行套件。 关键是要find如何使全球可用的摩卡接口(代码也可作为要点 )

 var Mocha = require("mocha"); var mocha = new Mocha(); var _suites = []; var _done = false; /** * default mocha options * for other configurations, check out bin/_mocha */ mocha.reporter("nyan"); mocha.useColors(true); mocha.growl(); module.exports = { /** * set interface (bdd is default) and make it global to node * @param {string} interface bdd|tdd|exports|qunit */ init: function(interface) { interface && mocha.ui(interface); mocha.suite.emit('pre-require', global, undefined, mocha); }, /** * add suite * @param {function} suite to be executed later */ add: function(suite) { mocha.suite && _suites.push(suite) && suite(); }, /** * run added suites */ run: function(cb) { console.info('run mocha'); var done = function () { _done = true; cb && cb(); process.on('exit', function() { console.info("exit mocha"); process.exit(1); }); }; mocha.run(done); }, /** * end mocha test */ exit: function() { if (_done) { process.exit(); } else { var start = new Date().getTime(), interval = setInterval(function() { if (_done) { console.log("test suites finished"); clearInterval(interval); process.exit(); } else if (new Date().getTime() - start > 5000) { console.log("wait for nothing!"); clearInterval(interval); process.exit(); } }, 250); } }, /** * change mocha options at runtime, eg, "reporter", "nyan" */ _set: function(key, val){ mocha[property](val); } };