Модульное тестирование вызова метода watch в функции Directive Link

0

У меня есть следующая Директива

.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);
            }
        };
    })

И вот Тест Единицы, который у меня есть.

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

И мой тест терпит неудачу, так как saveItems не вызван вообще. Не уверен, что я делаю неправильно.

Оцените любые входы.

благодаря

Теги:
unit-testing

1 ответ

0

Вы должны использовать угловое значение $timeout таким образом в своем тесте, ваш $timeout.flush() будет работать:

.directive("myContainer", function (myContainerService,$window, $timeout) {
    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;
                $timeout.cancel(timeout);
                timeout = $timeout(function () {
                    myContainerService.saveItems(items);
                }, 1000);
            }, true);
        }
    };
})

Ещё вопросы

Сообщество Overcoder
Наверх
Меню