user804401
user804401

Reputation: 1994

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.

Upvotes: 0

Views: 1060

Answers (2)

Narek Mamikonyan
Narek Mamikonyan

Reputation: 4611

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();

        });

Upvotes: 1

IMujagic
IMujagic

Reputation: 1259

You can compile your directive and click on it with jQuery, after that you can create spies on "modal" function, and expect that "modal" function would be called on the element. if you have something like this:

$(element).modal('show');

You can add spy on element and modal function and expect that modal will be called with 'show' parameter. And that's it for unit test, you just need to test if your logic works. If you need to test Modal component, and is it shown properly, that need to be tested in E2E tests.

Upvotes: 0

Related Questions