As part of my testing process, I am exploring a scenario where a service method is called using a local variable within an angular controller.
In this particular case, when the items array is empty, a modal for creating a new item will be triggered via the modal service.
Controller:
(function() {
'use strict';
angular
.module('app')
.controller('Item', Item);
//items is resolved through the ui-router resolve
//items contains a array of item objects. Will be an empty array if there are no items for that user
Item.$inject = ['items', 'modalService'];
function Item(items, modalService) {
var vm = this;
vm.items = items;
vm.newItemModal = modalService.newItemModal;
if (vm.items !== undefined) {
if (vm.items.length === 0) {
vm.newItemModal();
}
}
}
})();
vm.newItemModal() triggers the display of the new item modal. But how can I test this scenario using Jasmine?
Current Test Implementation:
describe('Controller: Item', function(){
var scope,
ctrl,
items,
modalService,
mockItems = [{ name: 'item1', desc:'desc1'}, { name: 'item2', desc:'desc2'}];
//mocking the modalService
beforeEach(function(){
module(function($provide){
modalService = {
newItemModal: function(){
return;
}
};
$provide.value('modalService', modalService);
});
});
beforeEach(inject(function(_$rootScope_, $controller) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
ctrl = $controller('Item as item', {
$scope: scope,
items: mockItems
});
}));
it('should verify the vm object', function(){
expect(scope.item.newItemModal).toBeDefined();
expect(scope.item.items).toEqual(mockItems);
});
//Separate test-suite as items is initialised with an empty array
describe('new item modal', function(){
beforeEach(inject(function(_$rootScope_, $controller) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
ctrl = $controller('Item as item', {
$scope: scope,
items: []
});
it('should open a new item modal', function(){
//returns 0
console.log('Items length', scope.items.length);
spyOn(scope.item, 'newItemModal').and.callThrough();
//testing this assertion fails
expect(scope.item.newItemModal).toHaveBeenCalled();
});
}));
});
});