天天看點

使用Async對Angular異步代碼進行單元測試

https://www.digitalocean.com/community/tutorials/angular-testing-async-fakeasync

The async utility tells Angular to run the code in a dedicated test zone that intercepts promises.

async可以讓Angular在一個專屬的test zone裡執行代碼,該zone可以截獲promises.

whenStable: allows us to wait until all promises have been resolved to run our expectations.

當所有的promises都resolved之後,whenStable觸發,能夠進行expectation的evaluation了。

看個例子:

import { Component } from '@angular/core';

@Component({

 selector: 'app-root',

 template: `

   set title

 `

})

export class AppComponent {

 title: string;

 setTitle() {

   new Promise(resolve => {

     resolve('One crazy app!');

   }).then((val: string) => {

     this.title = val;

   });

 }

}

使用Async對Angular異步代碼進行單元測試