jasmine测试抱怨undefined不是一个对象

jasmine test complaining with undefined is not an object

本文关键字:一个对象 undefined 测试 jasmine      更新时间:2023-09-26

我使用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不是对象(正在评估"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();
  });
})

表达式_this.tenant.divisible = _this.types[index].value;中的indexundefined,因为在测试中tenant.data被设置为空对象,并且没有divisible属性。当您在types上迭代时,您将type.value"undefined"进行比较,但找不到正确的类型。解决这个问题的一种方法是用正确的租户数据实例化控制器:

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