簡體   English   中英

為什么在單元測試中對instanceOf的測試失敗?

[英]Why does testing for instanceOf in my unit tests fail?

背景

我有一個具有一個getter函數的類,該函數返回用構造函數初始化的對象數組。 在單元測試中,我想驗證創建的子對象是該類的實例,但是由於某種原因, instanceOf返回的是false而不是true

編碼

我的課:

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() ,因為您要構建要返回的數組。 當您使用_.each()return語句實際上什么也不做,而_.each()只是返回原始數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM