如何在角度控制器内测试局部功能?

时间:2015-02-18 16:05:57

标签: angularjs karma-runner karma-jasmine

假设我有一个像:

这样的控制器
angular
    .module("app", [])
    .controller("NewsFeedController", [
        "$scope",
        "NewsFeedService",
        function ($scope, NewsFeedService) {
            $scope.news = [
                { stamp: 1 },
                { stamp: 9 },
                { stamp: 0 }
            ];

            $scope.onScroll = function () {
                /*
                    might do some stuff like debouncing, 
                    checking if there's news left to load, 
                    check for user's role, whatever. 
                */

                var oldestStamp = getOldestNews().stamp;
                NewsFeedService.getOlderThan(oldestStamp);

                /* handle the request, append the result, ... */
            };

            function getOldestNews () {
                /* code supposed to return the oldest news */
            }
        }
    ]);

getOldestNews被声明为本地函数,因为没有必要在$scope中公开它。

我该如何处理?我怎样才能真正测试这个功能?

describe("NewsFeedController", function () {
    beforeEach(module("app"));

    var $controller, $scope, controller;

    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
        $scope      = {};
        controller  = $controller("NewsFeedController", { $scope: $scope });
    }));

    it("should return the oldest news", function () {
        // How do I test getOldestNews?
    });
});

顺便说一句,如果解决方案也适用于服务和指令中的本地功能,那就太棒了。


相关问题:

1 个答案:

答案 0 :(得分:3)

现在,我在您的代码中看到了您真正想要做的事情。我不认为有必要测试私有函数,因为它没有足够的逻辑。我建议你只在NewsFeedService上创建一个间谍来测试正确的数据是否发送到该服务。

describe("NewsFeedController", function () {

    beforeEach(module("app"));

    var $controller, $scope, controller;
    var newsFeedServiceMock = jasmine.createSpyObj('NewsFeedService', ['getOlderThan']);

    beforeEach(inject(function (_$controller_) {
        $controller = _$controller_;
        $scope      = {};
        controller  = $controller("NewsFeedController", { $scope: $scope, NewsFeedService : newsFeedServiceMock });
    }));

    it("should return the oldest news", function () {
         $scope.news = [
            { stamp: 76 },
            { stamp: 4 },
            { stamp: 83 }
         ];

         $scope.onScroll();

         expect(newsFeedServiceMock.getOlderThan).toHaveBeenCalledWith(83);
    });
});

通过这种方式,您可以检查onScroll方法是否完成了正确的行为,而无需检查私有方法。您只想测试公共方法,因此当您想要创建私有方法来分离逻辑时,您可以灵活地使用,而无需更改测试。