Angular 2 Testing - Async function call - when to use

后端 未结 2 1034
自闭症患者
自闭症患者 2020-11-30 02:18

When do you use the async function in the TestBed when testing in Angular 2?

When do you use this?

 beforeEach(() => {
        Te         


        
2条回答
  •  萌比男神i
    2020-11-30 02:50

    When you make an async call in your test the actual test function is completed before the async call is completed. When you need to verify some state when the call was completed (which is usually the case) then the test framework would report the test as completed while there is still async work going on.

    With using async(...) you tell the test framework to wait until the return promise or observable is completed before treating the test as completed.

    it('should show quote after getQuote promise (async)', async(() => {
      fixture.detectChanges();
    
      fixture.whenStable().then(() => { // wait for async getQuote
        fixture.detectChanges();        // update view with quote
        expect(el.textContent).toBe(testQuote);
      });
    }));
    

    The code passed to then(...) will be executed after the test function itself completed. With async() you make the test framework aware, that it needs to wait for promises and observables to complete before treating the test as completed.

    See also

    • https://angular.io/guide/testing#async

提交回复
热议问题