Angular 1 / Jasmine / Karma - undefined不是一个对象

时间:2017-10-02 11:40:36

标签: angularjs unit-testing jasmine karma-runner karma-jasmine

在我的控制器中我有:

$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, satisfied: true}]

这个错误来自哪里?

2 个答案:

答案 0 :(得分:1)

api.php应该只是[Object{id: 35, satisfied: true}],而不是[{id: 35, satisfied: true}]Object是一个构造函数,所以你试图以错误的方式调用这个构造函数。看,第一个结构会引发错误。

错误的方式:

Object

正确的方式:

var foo = [Object{id: 35, satisfied: true}];
console.log(foo);

有关您尝试使用的Object构造函数的更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object

答案 1 :(得分:1)

解决方案:

scope.project = {
  realEstateProjectMotivation: {
    realEstateProjectOnSales: [
      {
        id: 35,
        satisfied: true
      }
    ]
  }
}

因为realEstateProjectMotivation提到real-estate-project-motivation="project.realEstateProjectMotivation"