javascript - Jasmine 测试提示 undefined is not an object

标签 javascript angularjs unit-testing jasmine

我使用 AngularJs,我需要像这样用 Jasmine 测试我的 init 元素:

var init = function () {
    _this.tenant = tenant.data;

    _this.types = [
      { value: "true", label: "Tenant" },
      { value: "false", label: "Project" }
    ];

    //Pre-select the good type
    var index;
    _.each(_this.types, function(data, idx) {
      if(_.isEqual(data.value, String(_this.tenant.divisible))) {
        index = idx;
      }
    });
    _this.tenant.divisible = _this.types[index].value;
  };
  init();

但是有一个错误:

undefined is not an object (evaluating 'a.types[t].value')

当我评论该行时:_this.tenant.divisible = _this.types[index].value; 所有测试构建成功。我无法正确测试这条线。

这是我的测试:

describe('Controller: TenantEditCtrl', function () {
  beforeEach(module('app'));

  var ctrl;
  var state;

  beforeEach(inject(function ($state, $controller, $rootScope) {
    state = $state.get('app.tenant_edit');
    //TODO: test with proper data
    ctrl = $controller('TenantEditCtrl', {
      $scope: $rootScope.$new(),
      tenant: {
        data: {}
      }
    });
  }));

  it('should initialize state properly', function () {
    expect(state.url).toEqual('/tenants/edit/:id');
  });

  it('should resolve data', function () {
    expect(ctrl.tenant).not.toBeNull();
  });

})

最佳答案

index in expression _this.tenant.divisible = _this.types[index].value;undefined 因为在测试中 tenant.data 设置为空对象并且没有 divisible 属性。当您遍历 types 时,您将 type.value"undefined" 进行比较,但找不到正确的类型。解决此问题的一种方法是使用正确的租户数据实例化 Controller :

  beforeEach(inject(function ($state, $controller, $rootScope) {
    state = $state.get('app.tenant_edit');
    ctrl = $controller('TenantEditCtrl', {
      $scope: $rootScope.$new(),
      tenant: {
        data: {
          // set divisible
          divisible: true
        }
      }
    });
  }));

关于javascript - Jasmine 测试提示 undefined is not an object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36690690/

相关文章:

javascript - 将元素 display none 改回默认样式值 JS

angularjs - 如何在 AngularJS 中注册我自己的事件监听器?

javascript - 如何使用模型中的函数表达式将函数动态绑定(bind)到 ng-click

android - Robolectric 和 Android Studio 1.1.0 和库测试

c# - 如何从[TestMethod]调用异步?

javascript - 如何使用 angularjs 将 JSON 对象中的日期与 "5/17/16"格式的日期进行比较?

"Function"关键字的 Javascript 别名

angularjs - 为什么我不能在 Firefox 中绑定(bind)到 Angular 模型的输入中输入文本?

node.js - 如何使用nodejs和mocha模拟另一个lambda函数内的aws lambda函数调用

JavaScript:检测 CSS3 动画何时结束