【问题标题】:Unit testing directive's controller单元测试指令的控制器
【发布时间】:2015-10-29 18:19:52
【问题描述】:

我正在努力从用于单元测试的指令中获取控制器。这是我的角度应用程序:

angular.module('test-app', [])

    .controller('loadingCtr', ['$scope', function ($scope) {

    }])

    .directive('loading', function() {
        return {
            restrict: 'E',
            controller: 'loadingCtr'
       };
    });

这是我的单元测试代码:

describe('loading', function () {

    beforeEach(inject(function($rootScope, $compile) {

        var fooElement = $compile('<loading></loading>')($rootScope);
        var fooController = fooElement.controller('loading');

        $rootScope.$digest();
        console.log(fooController);
    })); 

    describe('loading: testing loading directive', function() {
        it('should create loading directive', function() {
        });
    });
});

这里有一个 plnkr 可以玩弄:http://plnkr.co/edit/38cc5HQFgeHDhnC8OMo8?p=info

fooController 总是返回未定义。我尝试使用我在网上找到的以下示例,但我总是得到相同的结果:

Unit testing a directive that defines a controller in AngularJS

http://daginge.com/technology/2014/03/03/testing-angular-directive-controllers-with-jasmine-and-karma/

这里有什么我遗漏的明显东西吗?

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive jasmine karma-jasmine


    【解决方案1】:

    我能看到的唯一问题是你没有在你的夹具中加载模块test-app,这意味着编译的html代码并没有真正编译指令loading,因为它在注入器中不可用。所以尝试在beforeEach 块中加载模块。加载模块可确保在该模块下注册的指令、控制器、服务等在注入器中可用,否则它只会将该模块用作ng,它对loading 指令一无所知。

    describe('loading', function () {
       var fooController;
    
        //Load the module 
        beforeEach(module('test-app'));
    
        beforeEach(inject(function($rootScope, $compile) {
    
            var fooElement = $compile('<loading></loading>')($rootScope);
            fooController = fooElement.controller('loading');
    
            $rootScope.$digest();
            console.log(fooController);
        })); 
    
        describe('loading: testing loading directive', function() {
            it('should create loading directive', function() {
              expect(fooController).toBeDefined();
            });
        });
    });
    

    Demo

    另外请注意,如果您使用.controller 注册控制器,您可以通过$controller(ctrlName) 构造直接获取控制器实例。如果您在指令中使用controllerAs 语法和bindToController:true,那么您也可以从属性名称与别名相同的作用域中获取它。

    【讨论】:

      猜你喜欢
      • 2014-02-06
      • 2015-10-03
      • 1970-01-01
      • 2018-12-04
      • 2014-02-08
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      相关资源
      最近更新 更多