gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:05:45 27 4
gpt4 key购买 nike

背景

我有一个类,它有一个 getter 函数,该函数返回一个由构造函数初始化的 child 对象数组。在我的单元测试中,我想验证创建的子对象是该类的实例,但由于某种原因,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 语句,当你使用 _.each() 时,实际上什么都不做,_.each() 只是返回原始数组。

关于javascript - 为什么在我的单元测试中对 instanceOf 的测试失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29259647/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com