user804401 user804401 - 1 month ago 16
AngularJS Question

Unit testing Angularjs bootstrap Modal

I am having a directive in which there is a link which upon clicked shows data in a modal popup.

how to write unit tests(jasmine) for the link click and also how to test that model is opened and data in the modal is shown properly.

Could you provide any references.

Here is what I want to test

angular.module(’sample', [
'ui.bootstrap'
])
.controller(’ employeeController


', ['$scope', '$modal', function($scope, $modal) {

$scope.clickMe = function() {
var ModalInstanceCtrl = $modal.open({
templateUrl: ‘template/empView.html',
controller: ‘employeeController',
resolve: {
employees: function () {
return $scope.depEmps;
}
},
size: 'lg'
});
};

}]).directive(‘empInfo', function() {
return {
restrict: 'E',
templateUrl: ‘asdf,
replace: true,
controller: 'employeeController',
scope: {
employees: "="
}
};
})


I want to check that when ClickMe is called a model is opened and data is populated properly in the model. The model closes only on escape key press as of now.

Answer

At first you must create a modal mock:

function  ModalMock  {
    this.open = function(modalArgs) {
     return
   };
}

Then init this in your test:

beforeEach(() => {
        // create mocks
        modalMock = new ModalMock(); 
        controller = $controller('MyCtrl', {
        $scope: scope,
        $modal: modalMock,

     });

 });

And in actual test block you should use spyon method:

 it('should do something', function() {

            var modalPromise = q.defer().promise;

            spyOn(modalMock, 'open').andReturn({ result: modalPromise });

            controller.doSomething(arg);


            // make sure that angular resolves/rejects the deferreds
            scope.$digest();

            // verify that the modal is opened
            expect(modalMock.open).toHaveBeenCalled();

        });