单元在指令链接功能中测试监视方法调用

时间:2016-01-29 16:35:43

标签: angularjs unit-testing

我有以下指令

.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根本没有被调用。不确定我做错了什么。

感谢任何输入。

由于

1 个答案:

答案 0 :(得分: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);
        }
    };
})