2015-06-11 72 views
0

我正在嘗試使用Jasmine測試Angular指令。

HTML如下:

<html> 
    <head> 
     <title></title> 
     <script src='/jasmine/jasmine.js'></script> 
     <script src='/jasmine/jasmine-html.js'></script> 
     <script src='/jasmine/boot.js'></script> 
     <script src='/angular/angular.js'></script> 
     <script src='/angular/angular-mocks.js'></script> 
     <script src='/components/test-directive.js'></script> 
     <script src='/app.js'></script> 
     <script> 
      angular.module('myAppTests', ['myApp', 'ngMockE2E']) 
      .run(function($httpBackend){ 
       $httpBackend.whenGET(/^\/views\//).passThrough(); 
      }); 
     </script> 
     <script src='/components/test-directive.spec.js'></script> 
    </head> 
    <body></body> 
</html> 

測試指令(/components/test-directive.js)

angular.directive('testDirective', function(){ 
    return { 
     templateUrl:'/views/test-directive.html' 
    }; 
}); 

測試文件(/components/test-directive.spec.js )看起來是這樣的:

describe('test directive', function(){ 
    beforeEach(module('myAppTests')); 

    var element, $scope; 

    beforeEach(inject(function($compile, $rootScope){ 
     element = angular.element('<div data-test-directive=""></div>'); 
     $scope = $rootScope; 
     $compile(element)($scope); 
     $scope.$digest(); 
    })); 

    it('generates the correct HTML', function(){ 
     expect(element.html()).toContain('test content'); 
    }); 

}); 

而且/views/test-directive.html

<p>test content</p> 

運行測試時我得到以下錯誤:

'Unexpected request: GET /views/test-directive.html' 

回答

1

嘗試添加以下內容到過濾器:

$httpBackend.whenGET(/\.html$/).passThrough(); 
+0

感謝您的回答。雖然沒有運氣。仍然拋出相同的錯誤 – hofnarwillie

0

當您使用任何injectmodule在測試中,它含蓄加載ngMock的模塊,其中包括一個模擬的$ httpBackEnd,它不發送請求。

一種選擇是重用原始$ httpBackend。

angular.module('myAppTests', ['myApp', 'ngMock']) 
    .factory('$httpBackend', function() { 
    // use the original $httpBackend instead of the fake backend 
    return angular.injector(['ng']).get('$httpBackend'); 
    }); 
相關問題