2015-10-15 67 views
1

我目前遇到了一個問題,我無法獲得指令在標籤上運行。我是新來的單元測試和角度,所以請描述我做錯了什麼,或者我應該看看。使用httpBackend測試指令的角度單位

指令

.directive('documents', function(){ 
    return { 
     restrict: 'E', 
     templateUrl: '/abc/def/documents.html' 
    }; 
}) 

單元測試

beforeEach(module('myApp.home')); 
var $rootScope; 
beforeEach(inject(function (_$rootScope_) { 
    $rootScope = _$rootScope_; 
})); 

describe('Documents Directive', function(){ 
    var $compile; 
    beforeEach(inject(function (_$compile_, $httpBackend) { 
     $compile = _$compile_; 
     $httpBackend.when('GET', '/abc/def/documents.html').respond("What To Put here!"); 
    })); 

    it('Should call documents.html', function() { 
     var element = $compile("<documents>This should be hashed out</documents>")($rootScope); 
     console.log(element); 
     $rootScope.$digest(); 
     console.log(element); 
     console.log(element.html()); 
     expect(element.html()).toContain("Documents"); 
    }); 

}); 

documents.html

<h2>Documents</h2> 

運行測試時,這些都是我的結果:

INFO [watcher]: Changed file "C:/webroot/member_portal/app/home/home_test.js". 
LOG: Object{0: <documents class="ng-scope"></documents>, length: 1} 
LOG: Object{0: <documents class="ng-scope"></documents>, length: 1} 
LOG: '' 
Chrome 45.0.2454 (Windows 7 0.0.0) myApp.home module Documents Directive Should call documents.html FAILED 
    Expected '' to contain 'Documents'. 
     at Object.<anonymous> (C:/webroot/member_portal/app/home/home_test.js:265:36) 
Chrome 45.0.2454 (Windows 7 0.0.0): Executed 1 of 47 (1 FAILED) (skipped 46) ERROR (0.563 secs/0.01 secs) 

回答

1

下面的代碼按預期工作。您需要在致電$ httpBackend.flush()後調用您的期望;對/abc/def/documents.html的調用是一個異步調用,因此直到調用flush()之前它才被解析。

另一種解決方案是預先編譯模板文件。這將消除使用$ httpBackend的需要。你可以找到文檔here和搜索堆棧溢出大量的例子。

describe('', function(){ 

    beforeEach(module('myApp.home')); 
    var $rootScope; 
    beforeEach(inject(function (_$rootScope_) { 
     $rootScope = _$rootScope_; 
    })); 

    describe('Documents Directive', function(){ 
     var $compile, $httpBackend, expectedResults = '<h2>Documents</h2>'; 
     beforeEach(inject(function (_$compile_, _$httpBackend_) { 
      $compile = _$compile_; 
      $httpBackend = _$httpBackend_; 
      $httpBackend.expectGET('/abc/def/documents.html').respond(200, expectedResults); 
     })); 

     it('Should call documents.html', function() { 
      var $element = $compile("<documents>This should be hashed out</documents>")($rootScope); 
      $rootScope.$digest(); 
      $httpBackend.flush(); 
      expect($element.eq(0).html()).toEqual(expectedResults); 
     }); 

    }); 
});