【问题标题】:Unit test AngularJS controller that inherits from a base controller via $controller通过 $controller 从基本控制器继承的单元测试 AngularJS 控制器
【发布时间】:2015-02-02 12:28:27
【问题描述】:

场景是我有一个ChildCtrl 控制器,它从BaseCtrl 继承this inheritance pattern

angular.module('my-module', [])
    .controller('BaseCtrl', function ($scope, frobnicate) {
        console.log('BaseCtrl instantiated');

        $scope.foo = frobnicate();

        // do a bunch of stuff
    })

    .controller('ChildCtrl', function ($controller, $scope) {
        $controller('BaseCtrl', {
            $scope: $scope,
            frobnicate: function () {
                return 123;
            }
        });
    });

假设BaseCtrl 做了很多事情并且已经过很好的测试,我想测试ChildCtrl 用某些参数实例化BaseCtrl。我最初的想法是这样的:

describe("ChildCtrl", function () {
    var BaseCtrl;

    beforeEach(module('my-module'));

    beforeEach(module(function($provide) {
        BaseCtrl = jasmine.createSpy();
        $provide.value('BaseCtrl', BaseCtrl);
    }));

    it("inherits from BaseCtrl", inject(function ($controller, $rootScope) {
        $controller('ChildCtrl', { $scope: $rootScope.$new() });

        expect(BaseCtrl).toHaveBeenCalled();
    }));
});

但是,当我运行测试时,从未调用过间谍,并且控制台显示“BaseCtrl 已实例化”,这表明 $controller 使用的是实际控制器,而不是我为 $provide.value() 提供的实例。

最好的测试方法是什么?

【问题讨论】:

    标签: angularjs unit-testing inheritance jasmine


    【解决方案1】:

    所以看起来$controller 没有在$provide.value() 命名空间中按名称搜索控制器。相反,您必须使用 $controllerProvider.register() 方法,该方法只能从 module.config() 块访问。幸运的是,我们可以使用一个钩子来访问被测模块上的$controllerProvider

    更新后的测试代码如下:

    describe("ChildCtrl", function () {
        var BaseCtrl;
    
        beforeEach(module('my-module', function ($controllerProvider) {
            BaseCtrl = jasmine.createSpy();
            BaseCtrl.$inject = ['$scope', 'frobnicate'];
    
            $controllerProvider.register('BaseCtrl', BaseCtrl);
        }));
    
        beforeEach(inject(function ($controller, $rootScope) {
            $controller('ChildCtrl', { $scope: $rootScope.$new() });
        }));
    
        it("inherits from BaseCtrl", inject(function ($controller, $rootScope) {
            expect(BaseCtrl).toHaveBeenCalled();
        }));
    
        it("passes frobnicate() function to BaseCtrl that returns 123", function () {
            var args = BaseCtrl.calls.argsFor(0);
            var frobnicate = args[1];
    
            expect(frobnicate()).toEqual(123);
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 2015-03-15
      • 1970-01-01
      • 2013-03-01
      • 1970-01-01
      • 2014-10-08
      • 2016-07-25
      相关资源
      最近更新 更多