我使用 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/