用“暂停”来覆盖摩卡“it”来支持“yield”
在我的testing中使用暂停程序包处理asynchronous调用时,我想以更“干”的方式来编写规格。 例如下面的代码
it('works like fifo queue', function(done) { suspend.run(function*() { yield transport.enqueue({a:1}); yield transport.enqueue({b:1}); (yield transport.dequeue()).should.eql({a: 1}); (yield transport.dequeue()).should.eql({b: 1}); }, done); });
可以简化为:
it('works like fifo queue', function*() { yield transport.enqueue({a:1}); yield transport.enqueue({b:1}); (yield transport.dequeue()).should.eql({a: 1}); (yield transport.dequeue()).should.eql({b: 1}); });
如何覆盖摩卡的“it”函数来包装生成器函数?
好。 似乎它的function是全球性的。 所以这就是我最终如何解决的
// spec_helper.js var suspend = require('suspend'); // Add suspend support to "it-blocks" var originalIt = it; // remember the original it it = function(title, test) { // override the original it by a wrapper // If the test is a generator function - run it using suspend if (test.constructor.name === 'GeneratorFunction') { originalIt(title, function(done) { suspend.run(test, done); }); } // Otherwise use the original implementation else { originalIt(title, test); } }
然后在testing套件中,您可以:
require('spec_helper'); describe("Something", function() { it ("Supports generators", function*() { // Use yields here for promises ... }); it ("is compatible with regular functions", function() { // Can't use yields here ... }); });
我已经尝试了Igor S.的解决scheme,它的工作原理。
不过,我也发现有两个节点模块声称可以通过安装它们来解决这个问题:
- 共同摩卡
- 摩卡发电机
我试过后者,它也工作。 安装一个软件包比编写自定义代码更容易,不过理想的解决scheme是让mocha支持这个开箱即用的function。