如何模拟/存根 AngularJS 应用程序中的 activate() 方法

3
我目前正在开发一个大型的AngularJS应用程序,非常基于John Papa所写的 AngularJS Styleguide
他的建议之一是使用activate()方法作为每个控制器的引导程序。这使得您的代码结构清晰,并且您可以立即知道引导程序从哪里开始。通常情况下,我使用它来加载数据(我更喜欢这种方式而不是路由解析)。
我面临的问题是,在不运行activate()方法的情况下,如何对下面代码示例中的methodUnderTest()方法进行单元测试。
(function() {
    'use strict';

    angular
        .module('myApp', [])
        .controller('ControllerUnderTest', ControllerUnderTest);

    ControllerUnderTest.$inject = [];

    /* @ngInject */
    function ControllerUnderTest() {
        var vm = this;

        // attach functions to vm
        vm.activate = activate;
        vm.methodUnderTest = methodUnderTest;

        // activate
        activate();

        function activate() {
            // controller start-up logic
        }

        function methodUnderTest() {
            // how to test this method, without running the activate() method
        }
})();

以下是我目前拥有的测试代码,但正如你所预期的那样,它将总是运行activate()方法(这不是我想要的)。

(function() {

    var scope, createController;

    beforeEach(module('myApp'));

    describe('ControllerUnderTest', function(){
        beforeEach(inject(function($rootScope, $controller) {
            scope = $rootScope.$new();

            createController = function() {
                return $controller('ControllerUnderTest', { 'scope': scope });
            };
        }));

        it('should be defined', function() {
            var controller = createController();
            expect(controller).toBeDefined();
        });

        it('should have a methodUnderTest', function() {
            var controller = createController();
            expect(controller.methodUnderTest).toBeDefined();
        });

    });
})();

如何在不运行activate()方法的情况下测试ControllerUnderTest.methodUnderTest()

你必须在activate方法内部模拟所有调用,不执行初始化方法不是一个好的测试。 - fantarama
谢谢fantarama,但如果activate()方法中有很多事情发生,并且涉及许多不相关的依赖项(服务),这些依赖项并不对methodUnderTest有用,该怎么办? - Vadiem Janssens
1
对于测试无用的服务必须使用void实现或固定返回值进行模拟。 - fantarama
谢谢Fantarama。如果您在答案中提供评论,我将很高兴将此帖标记为已回答。 - Vadiem Janssens
1个回答

1
在模块单元测试中,您需要模拟所有超出测试范围的依赖关系。
例如:
beforeEach(module(function ($provide) {
    $provide.service("myService", function () {
        this.myMethod = function () {
            return "myValue";
        };
    });
}));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接