【问题标题】:Override mocha "it" to support "yield" using "suspend"使用 "suspend" 覆盖 mocha "it" 以支持 "yield"
【发布时间】:2014-05-26 07:58:48
【问题描述】:

在我的测试中使用暂停包处理异步调用时,我想以更“干”的方式编写规范。比如下面的代码

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

如何覆盖 mocha 中的“it”函数来包装生成器函数?

【问题讨论】:

  • 为什么可以简化成那样?
  • 我相信它可以。虽然我不知道覆盖“it”功能的正确点是什么。类似于:var originalIt = XXX.it; XXX.it = function(title, gen) { originalIt(title, suspend.run(gen, done); }
  • suspend本身也返回一个函数,所以你可以这样做it('...', suspend(function*(){ ... }));
  • @loganfsmyth 这行不通。它将导致所有测试成功,因为不会出现异常。所以你需要通过 done 函数来挂起,它使每个测试用例的代码变得复杂。
  • @IgorS。它将捕获异常,然后将它们作为第一个参数传递给doneit('should fail', suspend(function * (){ throw new Error("FAILED"); })); 对我来说失败了。

标签: node.js generator mocha.js yield suspend


【解决方案1】:

好的。似乎 it 函数是全局的。所以这就是我最终解决它的方法

// 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);
  }
}

然后在你做的测试套件中:

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

【讨论】:

    【解决方案2】:

    我已经尝试了Igor S. 的解决方案,它确实有效。

    但是,我还发现有两个节点模块声称可以通过安装来解决此问题:

    我尝试了后一种,它也有效。也许安装包比编写自定义代码更容易,尽管理想的解决方案是 mocha 开箱即用地支持这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-08
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      • 2018-03-16
      • 2015-08-12
      • 2012-02-12
      • 1970-01-01
      相关资源
      最近更新 更多