Reputation: 437
I use AngularJs and i need to test element of my init with Jasmine like this :
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();
but there is an error :
undefined is not an object (evaluating 'a.types[t].value')
When i comment the line : _this.tenant.divisible = _this.types[index].value;
all test build successful. I'm not be able to test this line correctly.
This is my test :
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();
});
})
Upvotes: 1
Views: 497
Reputation: 1402
index
in expression _this.tenant.divisible = _this.types[index].value;
is undefined
because in tests tenant.data
is set to empty object and doesn't have divisible
property. When you iterate over types
you compare type.value
to "undefined"
and can't find correct type. One way to fix this is to instantiate controller with correct tenant data:
beforeEach(inject(function ($state, $controller, $rootScope) {
state = $state.get('app.tenant_edit');
ctrl = $controller('TenantEditCtrl', {
$scope: $rootScope.$new(),
tenant: {
data: {
// set divisible
divisible: true
}
}
});
}));
Upvotes: 2