2015-10-15 88 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