angularjs - 如何在 AngularJS 应用程序中模拟/ stub activate() 方法

标签 angularjs unit-testing jasmine tdd

我目前正在开发一个大型 AngularJS 应用程序,它很大程度上基于优秀的 AngularJS Styleguide by John Papa .

他的一个建议是使用 activate() 方法作为每个 Controller 的一种 Bootstrap 。这使您的代码结构清晰,您立即知道 Bootstrap 从哪里开始。很多时候,我用它来加载数据(我更喜欢这个而不是路由解析)。

我面临的问题是如何在不运行 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()

最佳答案

在模块单元测试中,您必须模拟所有超出测试范围的依赖项。

有点像:

beforeEach(module(function ($provide) {
    $provide.service("myService", function () {
        this.myMethod = function () {
            return "myValue";
        };
    });
}));

关于angularjs - 如何在 AngularJS 应用程序中模拟/ stub activate() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38225954/

相关文章:

angularjs - 设置 Angular 基础以使用带有 Angular 的显示模态

angularjs - 使用对象数组中的 ID 设置 ui-select 值

Angular 2 RC5 测试 Promise 在 ngOnInit 中不起作用

angularjs - $uibModal 尝试在我的表单中强制执行提交

angularjs - 模态 Controller 中的 $setValidity [AngularJS]

java - Spring Boot 中的完整验证测试,注入(inject)失败

unit-testing - 类内部的python单元测试方法

java - Powermock 的问题

angular - 如何对在 Angular 中使用 Router 的组件进行单元测试?

angular - 如何在 Karma 中运行特定的测试文件? ( Angular 4+)