2015-12-21 74 views
2

我開始了一個新的Angular 2應用程序。我有一個簡單的組件,基本上是一個下拉選擇框。該組件將幾個對象作爲屬性(在應用程序中,通過包含模板中組件DOM元素的屬性)。在ES5中測試Angular 2組件?

Angular 2的官方文檔還沒有測試組件的示例。我將如何測試組件的實際視圖 - 檢查是否根據組件上設置的數據創建適當的DOM元素?

我可以通過做ng.core.Injector.resolveAndCreate([...dependencies...]).get(MyClassName)來創建我的組件之一。但是這實際上並不構建視圖,或者讓我傳入要設置爲剛剛創建的組件的屬性的數據。

回答

4

以下您在文檔和回購源代碼中看到的內容並不困難。這是我做的設置,它的工作原理。

從文檔首先,我把茉莉例如設置

<link rel="stylesheet" href="node_modules/jasmine-core/lib/jasmine-core/jasmine.css"> 
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script> 
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script> 
<script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script> 

然後angular2的設置。您可能已經知道,當您在ES5中編寫時,您必須使用UMD捆綁包

<script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> 
<script src="node_modules/rxjs/bundles/Rx.umd.min.js"></script> 
<script src="node_modules/angular2/bundles/angular2-all-testing.umd.dev.js"></script> 

現在是重要的部分,測試。這裏的主要任務是創建一個測試組件

var TestComponent = ng.core. 
    Component({ 
     selector: 'cmp', 
     template : '' // Left it blank, we override it when testing 
    }).Class({ 
     constructor: function() { 
      this.someProperty = 'Initial value'; 
     } 
    }); 

創建組件後,可以通過使用TestComponentBuilder

ng.testing.describe('Component building', function() { 

    ng.testing.it('should detect when a property changes', 
     ng.testing.inject([ng.testing.TestComponentBuilder], function(tcb) { 
      tcb 
       .overrideTemplate(TestComponent, '<div>{{someProperty}}</div>') 
       .createAsync(TestComponent) 
       .then(function(fixture) { 

        // Triggers change detection so 
        // the div actually contains the property value 
        fixture.detectChanges(); 

        // Check if the div contains the correct value 
        expect(fixture.nativeElement.innerText).toEqual('Initial value'); 

        // Change property's value 
        fixture.componentInstance.someProperty = 'New value'; 

        // Triggers change detection again 
        fixture.detectChanges(); 

        // Check, again, if the div contains the new value 
        expect(fixture.nativeElement.innerText).toEqual('New value'); 
       }); 
     })); 
}); 

請注意,我使用ng.testing.(describe/it/etc)因爲茉莉花這些功能進行了修補測試與angular2一起工作。

從這一點開始,超級容易繼續。你已經有完整的回購看到他們specs。有趣的是NgFor。你可以按照TS/ES6的例子,它們是一樣的。

這是一個plnkr與repro工作。

參考

可以檢查以及朱莉拉爾夫的repo (ng2-test-seed)和她talk at AngularConnect 2015

我希望它能幫助。

+0

謝謝,這非常有幫助!我不確定你在討論什麼文檔,但https://angular.io/docs/ts/latest/testing/上的「測試指南」沒有關於測試組件,服務或DOM的部分然而。 –

+0

對不起!我的意思是設立茉莉花的部分(我從文檔中獲得)!很高興幫助:) –

+0

快速追蹤:爲什麼需要'overrideTemplate'?當我刪除它時,'.then('似乎沒有被解僱,我怎樣才能在測試中使用我的原始組件html模板? –