2017-07-15 90 views
1

我正在爲一個應用程序編寫jasmine/karma/webpack單元測試,其中有許多內部承諾在代碼中深入解析。我想使用角度的異步,fixture.detectChanges和fixture.whenStable。angular 4.3.0在執行異步函數後調用fixture.whenStable

作爲一個概念證明,我做了以下簡單但非常異步的組件。

import {Component} from "@angular/core"; 
import {Logger} from "../../utils/logger"; 

@Component({ 
    selector: 'unit-test.html', 
    template: `  
    <div class="unit-test"> 
    <h3>Unit Test Component</h3> 
    <h4>p1: {{p1}}</h4> 
    <h4>v1: {{v1}}</h4> 
    <h4>p2: {{p2}}</h4> 
    <h4>v2: {{v2}}</h4> 
    <h4>p3: {{p3}}</h4> 
    <h4>v3: {{v3}}</h4> 
    </div>` 
}) 
export class UnitTestComponent { 
    p1: Promise<string>; 
    v1: string; 
    p2: Promise<string>; 
    v2: string; 
    p3: Promise<string>; 
    v3: string; 

    constructor() { 
    this.p1 = makeTimeoutPromise('value1', 2000); 
    Logger.warn('p1 created'); 
    this.p1.then(data => { 
     this.v1 = data 
    }); 
    } 

    method2() { 
    this.p2 = makeTimeoutPromise('value2', 2000); 
    this.p2.then(data => { 
     this.v2 = data 
    }); 
    Logger.warn('p2 created'); 
    } 

    method3() { 
    this.p3 = makeTimeoutPromise('value3', 2000); 
    this.p3.then(data => { 
     this.v3 = data 
    }); 
    Logger.warn('p2 created'); 
    } 
} 


function makeTimeoutPromise(result: string, timeout: number) { 
    return new Promise<string>((resolve, reject) => { 
    setTimeout(() => { 
     resolve(result); 
     Logger.warn(`resolved '${result}' after '${timeout}' seconds`); 
    }, timeout) 
    }); 
} 

爲了測試這個,我在異步塊中創建了組件。這是有效的,並且在構造函數的承諾解決之後,它會開始運行。

在測試內部,我調用comp.method2(),它導致承諾在2秒後解決。然而......這裏是我沒有得到的部分......在調用comp.method2()後立即調用fixture.isStable()返回true。我本來預計會錯誤的。更糟.... fixture.whenStable()立即解析。由於實際方法中的承諾尚未解決,我還沒有想要測試的價值。

import {UnitTestComponent} from './unit-test.component'; 
import {async, ComponentFixture, TestBed, tick} from '@angular/core/testing'; 
import {DebugElement} from '@angular/core'; 

describe('UnitTestComponent',() => { 
    let de: DebugElement; 
    let comp: UnitTestComponent; 
    let fixture: ComponentFixture<UnitTestComponent>; 
    let el: HTMLElement; 
    const startTime = Date.now(); 
    beforeEach(async(() => { 
    console.log('time beforeEach.start', Date.now() - startTime); 
    const testbed = TestBed.configureTestingModule({ 
     declarations:[UnitTestComponent], 
     imports: [], 
     providers: [] 
    }); 
    // testbed.compileComponents(); 
    console.log('time beforeEach.initSsmpComponentLibModule', Date.now() - startTime); 
    fixture = TestBed.createComponent(UnitTestComponent); 
    comp = fixture.componentInstance; 
    de = fixture.debugElement; 
    console.log('time beforeEach.end', Date.now() - startTime); 
    })); 

    it('should create the component', async(() => { 
    // const x = new Promise<any>((resolve, reject)=>{ 
    // setTimeout(()=>{ 
    //  console.log('right before exit', comp); 
    //  fixture.detectChanges(); 
    //  resolve(); 
    //  }, 10000); 
    // }); 
    console.log('time it.start', Date.now() - startTime, comp); 
    expect(comp).toBeDefined(); 
    console.log('fixture.isStable() (1)', fixture.isStable()); 
    comp.method2(); 
    console.log('fixture.isStable() (2)', fixture.isStable()); 
    fixture.whenStable() 
     .then(data=>{ 
     fixture.detectChanges(); 
     console.log('time after whenStable(1) resolves', Date.now() - startTime, comp); 
     fixture.detectChanges(); 
     console.log('time after whenStable(1).detect changes completes', Date.now() - startTime, comp); 
     expect(comp.v2).toBe('value2'); 
     comp.method3(); 
     console.log('method3 called', Date.now() - startTime, comp); 
     fixture.detectChanges(); 
     console.log('time after detectChanges (2)', Date.now() - startTime, comp); 
     fixture.whenStable() 
      .then(data=>{ 
      fixture.detectChanges(); 
      console.log('time after whenStable(3).then', Date.now() - startTime, comp); 
      expect(comp.v3).toBe('value3'); 
      }); 
     console.log('time after whenStable(3)', Date.now() - startTime, comp); 

     }); 
    console.log('time after whenStable(2)', Date.now() - startTime, comp); 
    })); 


}); 

控制檯日誌輸出如下。我期待

fixture.isStable() (2) false 
time after whenStable(2) >=4386 UnitTestComponent {p1: ZoneAwarePromise, v1: "value1", p2: ZoneAwarePromise} 

,但得到

fixture.isStable() (2) true 
time after whenStable(2) 2390 UnitTestComponent {p1: ZoneAwarePromise, v1: "value1", p2: ZoneAwarePromise} 

time beforeEach.start 363 
time beforeEach.initSsmpComponentLibModule 363 
time beforeEach.end 387 
time it.start 2386 UnitTestComponent {p1: ZoneAwarePromise, v1: "value1"} 
fixture.isStable() (1) true 
fixture.isStable() (2) true 
time after whenStable(2) 2390 UnitTestComponent {p1: ZoneAwarePromise, v1: "value1", p2: ZoneAwarePromise} 
time after whenStable(1) resolves 2393 time beforeEach.start 363 

沒有comp.method2的顯性知識()的內部,我怎麼能有角等到所有的承諾從解決方法在裏面調用它()方法?我認爲這是fixture.whenStable的明確作用。

回答

0

回答我自己的問題。當然!我沒有在一個區域中跑步。所以有兩種方法可以解決這個問題。 (我證明了兩者)。

解決方案1:獲取本地元素並單擊它.....如果您正在測試瀏覽器事件。 (所以我添加使用

const button = de.query(By.css('#unit-test-method-2-button')); 
expect(button).toBeDefined(); 
button.nativeElement.click(); 

的我需要更好的解決方案是簡單地注入NgZone

<button id='unit-test-method-2-button'(click)="method2()">Method 2</button> 

然後叫方法2()。這讓我做嵌套調用fixture.whenStable( )。

因此我加

beforeEach(inject([NgZone], (injectedNgZone: NgZone) => { 
    ngZone = injectedNgZone; 
})); 

這讓我打電話給異步方法2,一d然後異步method3,並使用fixture.whenStable ...

it('should create the component', async(() => { 
    ngZone.run(() => { 
    console.log('time it.start', Date.now() - startTime, comp); 
    expect(comp).toBeDefined(); 
    expect(fixture.isStable()).toBe(true, 'expect fixture to be stable'); 
    comp.method2(); 
    expect(fixture.isStable()).toBe(false, 'expect fixture not to be stable'); 
    fixture.whenStable() 
     .then(data => { 
     fixture.detectChanges(); 
     expect(comp.v2).toBe('value2'); 
     comp.method3(); 
     fixture.whenStable() 
      .then(data => { 
      fixture.detectChanges(); 
      expect(comp.v3).toBe('value3'); 
      }); 
     }); 
    }); 
}));