Angular 1/Jasmine/Karma - undefined 不是对象
2017-10-02
69
在我的控制器中,我有:
$onInit() {
this.doShowInfoMsg()
}
doShowInfoMsg() {
return this.checkProjectOnSalesLength = this.realEstateProjectMotivation.realEstateProjectOnSales.length < 1
}
在我的单元测试(极简主义)中:
describe('iadMyIadProjectMotivationsHowSaleCurrentCapitalDetail', () => {
let scope
let compile
let element
let ctrl
beforeEach(() => {
angular.mock.module('projectMotivationsHowSaleCurrentCapitalModule')
})
beforeEach(inject(($componentController) => {
let bindings = {
realEstateProjectMotivation: {
realEstateProjectOnSales: [
{
id: 35,
satisfied: true
}
]
}
ctrl = $componentController('projectMotivationsHowSaleCurrentCapitalDetail', null, bindings)
}))
})
错误:
TypeError: undefined is not an object (evaluating 'this.realEstateProjectMotivation.realEstateProjectOnSales')
但是当我执行
console.log (ctrl.realEstateProjectMotivation.realEstateProjectOnSales)
时,我有定义明确的数组
realEstateProjectOnSales
:
LOG: [Object{id: 35, satisfaction: true}]
这个错误从何而来?
2个回答
[Object{id: 35, satisfied: true}]
应为
[{id: 35, satisfied: true}]
,不包含
Object
。
Object
是构造函数,因此您尝试以错误的方式调用此构造函数。看,使用第一个结构会引发错误。
错误方式:
var foo = [Object{id: 35, satisfied: true}];
console.log(foo);
正确方式:
var foo = [{id: 35, satisfied: true}];
console.log(foo);
有关您尝试使用的 Object 构造函数的更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
P.S.
2017-10-02
解决方案:
scope.project = {
realEstateProjectMotivation: {
realEstateProjectOnSales: [
{
id: 35,
satisfied: true
}
]
}
}
因为
realEstateProjectMotivation
引用了
real-estate-project-motivation="project.realEstateProjectMotivation"
Mouad Ennaciri
2017-10-02