vendredi 29 janvier 2016

Unit Testing a watch method call in Directive link function

I have the following Directive

.directive("myContainer", function (myContainerService,$window) {
        return {
            restrict: 'A',
            templateUrl: "myContainer/MyContainer.tpl.html",
            controller: 'myCtrl',
            controllerAs: 'myCtrl',
            scope: {
                items: '='
            },
            link: function (scope, element) {

                var timeout;
                scope.$watch('myCtrl.items', function (items) {
                    var windowWidth = $window.innerWidth - 65;
                    window.clearTimeout(timeout);
                    timeout = window.setTimeout(function () {
                        myContainerService.saveItems(items);
                    }, 1000);
                }, true);
            }
        };
    })

And here is the Unit Test i have.

describe("myCtrl", function(){
        var myCtrl;
        var dirEle ;
        var myScope;
        // var to store the Mock Items
        var myContainerService = $injector.get('myContainerService');
        var items = [..]
        beforeEach(inject(function($compile, $httpBackend){
              $httpBackend.whenGET(/.*my-app\/restful-services\/items*./).respond({...});
            scope.items = myContainerService.getItems();
            dirEle = $compile('<div my-container items="items"></div>')(scope);

            scope.$digest();
            myScope = dirEle.isolateScope();
            myCtrl  = myScope.myCtrl;
        }));

        fit("Saving Items", inject(function($timeout){
            spyOn(myContainerService, 'saveItems');
            //$timeout.flush();
            myScope.$digest();
            $timeout.flush();
            expect(myContainerService.saveItems).toHaveBeenCalledWith(myCtrl.items);
        }));
    });

And my test is failing as the saveItems is not getting called at all. Not sure what i am doing wrong.

Appreciate any inputs.

Thanks

Aucun commentaire:

Enregistrer un commentaire