簡體   English   中英

使用fakeAsync進行Angular2測試

[英]Angular2 testing with fakeAsync

我正在嘗試使用fakeAsync測試Angular 2組件,但是沒有設置夾具變量。 實際上,沒有調用promise回調。 這是代碼:

@Component({
  template: '',
  directives: [GroupBox, GroupBoxHeader]
})
class TestComponent {
  expandedCallback() { this.expandedCalled = true; }
}

it('testing...', inject([TestComponentBuilder], fakeAsync((tcb) => {

  var fixture;

  tcb.createAsync(TestComponent).then((rootFixture) => {
    fixture = rootFixture
  });

  tick();

  fixture.detectChanges();
})));

運行此代碼時,我得到:

失敗:無法讀取未定義類型的屬性“ detectChanges”錯誤:無法讀取未定義的屬性“ detectChanges”

我不知道為什么不觸發回調。 在此存儲庫中,它可以正常工作: https : //github.com/juliemr/ng2-test-seed/blob/master/src/test/greeting-component_test.ts

有什么線索嗎?

注意:我正在使用ES6,Traceur,Angular 2 beta,Karma和Jasmine。

------更新------

它遵循測試失敗的存儲庫:

https://github.com/cangosta/ng2_testing_fakeasync

TestComonentBuilder不適用於templateUrl https://github.com/angular/angular/issues/5662

嘗試這種方式https://github.com/antonybudianto/angular2-starter/blob/master/app/simplebind/child.component.spec.ts#L15

關鍵是要創建一個測試虛擬組件(例如TestComponent ),然后在directives: [...]注冊要測試的組件,並使用template: <my-cmp></my-cmp> ,然后傳遞TestComponenttsb.createAsync(TestComponent)... ,並使用injectAsync

我更喜歡這種方式,因為我可以輕松地模擬來自父級的數據,並向/從組件傳遞任何輸入和處理輸出。

 import { it, injectAsync, describe, expect, TestComponentBuilder, ComponentFixture } from 'angular2/testing'; import { Component } from 'angular2/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'test', template: ` <child text="Hello test" [(fromParent)]="testName"></child> `, directives: [ChildComponent] }) class TestComponent { testName: string; constructor() { this.testName = 'From parent'; } } let testFixture: ComponentFixture; let childCompiled; let childCmp: ChildComponent; describe('ChildComponent', () => { it('should print inputs correctly', injectAsync([TestComponentBuilder], (tsb: TestComponentBuilder) => { return tsb.createAsync(TestComponent).then((fixture) => { testFixture = fixture; testFixture.detectChanges(); childCompiled = testFixture.nativeElement; childCmp = testFixture.debugElement.children[0].componentInstance; expect(childCompiled).toBeDefined(); expect(childCmp).toBeDefined(); expect(childCompiled.querySelector('h6')) .toHaveText('From parent'); expect(childCompiled.querySelector('h5')) .toHaveText('Hello test'); }); })); it('should trigger changeMe event correctly', () => { childCmp.changeMe(); testFixture.detectChanges(); expect(childCmp.num).toEqual(1); expect(childCompiled.querySelector('h6')) .toHaveText('Changed from child. Count: ' + childCmp.num); }); }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM