[英]Test Angular 2 component in ES5?
我正在啟動一個新的Angular 2應用程序。 我有一個簡單的組件,它實際上是一個下拉選擇框。 組件將一些對象作為屬性(在應用程序中,通過包含模板中組件DOM元素上的屬性)。
Angular 2的官方文檔尚無測試組件的示例。 我將如何測試組件的實際視圖-檢查是否根據在組件上設置的數據創建了適當的DOM元素?
我可以通過執行ng.core.Injector.resolveAndCreate([...dependencies...]).get(MyClassName)
來創建組件之一。 但這實際上並不能構造視圖,也不能讓我傳入要設置為剛創建的組件屬性的數據。
遵循您在文檔和回購源代碼中看到的內容並不困難。 這是我所做的設置,它可以正常工作。
首先從文檔中,我選擇了茉莉花示例設置
<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)
因為來自jasmine的這些功能已修補為可與angular2一起使用。
從這一點開始,將非常容易繼續。 您已經擁有整個倉庫,可以查看其規格 。 NgFor是一個有趣的例子 。 您可以遵循TS / ES6示例,它們是相同的。
這是帶有復制功能的plnkr 。
參考
您也可以在AngularConnect 2015上查看Julie Ralph的回購(ng2-test-seed)和她的演講
希望對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.