2015-10-15 72 views
0

我有一个指令,其中控制器被定义为指令定义的一部分。单元测试使用Karma的角度Js控制器

(function(){ 
    var app = angular.module('app', []); 
    app.directive('test', function(){ 
    return { 
    restrict: 'E', 
    templateUrl: 'test.html', 
    controller: ['$scope', function ($scope){...*set of functions*......}], 
    controllerAs:'reportCtrl', 
    link:function(Attrs){ 
     } 
    }; 
    }); 
})(); 

我需要为这组函数编写单元测试。我不熟悉业力测试,并没有为这类代码找到很多资源。我几乎尝试了所有可能的方式。有人可以帮我写这个单元测试

+0

[角JS单元测试控制器]的可能的复制(http://stackoverflow.com/questions/33134566/angular-js-unit-testing-a-controller) – angmerica

回答

0

这里是一个例子。见演示http://plnkr.co/edit/zK9MNkvNpHF2UY9BgMKz?p=preview

我所做的是编译指令并称为摘要循环。 安装完成后,它与常规控制器几乎相同。

describe('Auth Service Tests', function() { 
    var element; 
    var isolated; 
    var $scope; 
    beforeEach(module('MyApp')); 
    beforeEach(inject(function($rootScope, $compile, $templateCache) { 
    // Imports test.html 
    var templateUrl = 'test.html'; 
    var req = new XMLHttpRequest(); 
    req.onload = function() { 
     $templateCache.put(templateUrl, this.responseText); 
    }; 
    req.open('get', templateUrl, false); 
    req.send(); 


    $scope = $rootScope.$new(); 

    element = '<test></test>'; 
    // Creates the directive. 
    element = $compile(element)($scope); 

    // activates the $digest cycle. 
    $scope.$apply(); 
    })); 

    it('tests the transclude', function() { 
    expect($scope.apple).toEqual('world'); 
    expect($scope.getApple()).toEqual('world'); 
    }); 

}); 
+0

谢谢。我有模板Url:../test/test/test.html,我正在将单元测试写入不同的文件夹。我应该从$ templateCache.put中的单元测试文件夹中提供test.html的路径。我收到一个错误意外的请求:GET ../test/test/test.html – vino

+0

是的,你应该改变例子以适合你的路径。或者你可以使用ngHtml2JsPreprocessor。 http://stackoverflow.com/questions/15214760/unit-testing-angularjs-directive-with-templateurl这将把你的html转换成js,并把它放到一个单独的模块中。这样你不必使用$ templateCache。 – angmerica

+0

如果我们使用ngHtml2JsPreprocessor,那么我们只需要加载模块,我们可以避免模板缓存权利? – vino