【问题标题】:Unit testing generators with `return` and `yield`带有“return”和“yield”的单元测试生成器
【发布时间】:2017-07-07 13:46:33
【问题描述】:

鉴于此功能

function* backflip(query) {
  return yield 123;
}

还有这个测试

describe('backflip', () =>
  it('should do that ^', () =>
    let handlerInstance = handler();
    expect(handlerInstance.next().value).to.equal(123);
    expect(handlerInstance.next().done).to.equal(true);
  );
);

伊斯坦布尔,应该说所有分支都被覆盖,但实际上这覆盖了 4 个中的 3 个。删除 return 解决了这个问题。

  • returnyield 一起是反模式吗?
  • 这是一个错误吗?

对于上下文,Babel 将其编译为

"use strict";

var _marked = [backflip].map(regeneratorRuntime.mark);

function backflip(query) {
  return regeneratorRuntime.wrap(function backflip$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          _context.next = 2;
          return 123;

        case 2:
          return _context.abrupt("return", _context.sent);

        case 3:
        case "end":
          return _context.stop();
      }
    }
  }, _marked[0], this);
}

【问题讨论】:

  • 您如何使用覆盖率跟踪对代码进行注释?
  • 您可以在编译代码中看到case 3 永远无法到达。您应该只关心您编写的代码的代码覆盖率,而不是生成的代码。

标签: unit-testing ecmascript-6 generator babeljs istanbul


【解决方案1】:

来自控制台的快速示例:

var g = function* backflip(query) {
    yield 123; return 0;
};
undefined
var a = g();
undefined
a.next()
Object {value: 123, done: false}
a.next()
Object {value: 0, done: true}
a.next()
Object {value: undefined, done: true}

生成器还有 1 个状态。

【讨论】:

    【解决方案2】:

    这是一个正在解决的错误。该分支目前无法测试。

    【讨论】:

      猜你喜欢
      • 2017-07-07
      • 1970-01-01
      • 2021-09-05
      • 2017-08-29
      • 1970-01-01
      • 2011-11-02
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多