node.js - 使用 "it"覆盖 mocha "yield"以支持 "suspend"

标签 node.js generator mocha.js yield suspend

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

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 功能是全局的。所以这就是我最终解决的方法

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

关于node.js - 使用 "it"覆盖 mocha "yield"以支持 "suspend",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23024847/

相关文章:

javascript - Node 代理服务器,瓶颈?

Android,随机不会连续两次重复相同的数字

javascript - 单元测试语法错误: Unexpected token {

node.js - 在 visual studio 中正确配置 mocha.json 以进行 sails.js 应用程序测试

javascript - Node.js + express : Trying to Properly Display GET Request Headers

deployment - 当我希望使用 node.js 在我的项目中部署库时,应该包含哪些文件?

javascript - 无法读取 gulp 中未定义的属性 'watch'

python - 忽略来自生成器的异常

python - 为什么 numpy 的 fromiter 函数需要指定 dtype 而其他数组创建例程不需要?

reactjs - 在 React 和 Redux 中使用 Enzyme 进行嵌套组件测试