为什么在我的单元测试中对 instanceOf 的测试失败了?

Why does testing for instanceOf in my unit tests fail?

背景

我有一个 class,它有一个 getter 函数,returns 一个由构造函数初始化的 child 对象数组。在我的单元测试中,我想验证创建的子对象是 class 的实例,但由于某种原因,instanceOf 返回 false 而不是 true

代码

我的class:

function Class(data) {
  this.data = data
}

Class.prototype = {
  get children() {
    return _.each(this.data.children, function(child) {
      return new Class(child);
    });
  }
}

我的测试:

it('should instantiate each child', function() {
  var classInstance = new Class({
    children: [
      /* ... */
    ]
  });

  classInstance.children.forEach(function (child) {
    expect(child).to.be.an.instanceOf(Class);  //THIS FAILS
  });
});

有趣的是,expect(classInstance).to.be.an.instanceOf(Class); 通过了。这是什么原因?

我认为你的测试失败了,因为它应该失败。我认为您的 getter 函数应该如下所示:

return _.map(this.data.children, function(child) {
  return new Class(child);
});

也就是_.map()而不是_.each(),因为你想建立一个数组到return。 return 语句,当你使用 _.each() 时,实际上什么都不做,而 _.each() 只是 return 原始数组。