Angular Unit Test 单元测试异步方法
点我测试对象代码 .
import { AsyncService } from './async.service' ;
describe ( 'AsyncService' , ( ) => {
let service: AsyncService;
beforeEach ( ( ) => {
service = new AsyncService ( ) ;
} ) ;
it ( ' test synchronousGet ' , ( ) => {
var input: string = "测试同步方法" ;
var expected: string = input;
var output: string = service. getData ( input) ;
expect ( output) . toBe ( expected) ;
} ) ;
it ( ' test async by callback' , ( done: DoneFn) => {
var input: string = "测试用callback形式实现的异步方法" ;
var timeout= 1000 ;
var expected: string = `data= ${ input} , timeout= ${ timeout} ` ;
var output: string = '' ;
service. getDataAsyncByCallback ( input, ( data: string ) => {
output = data;
expect ( output) . toBe ( expected) ;
done ( ) ;
} , timeout) ;
} ) ;
it ( ' test async by Promise' , ( done: DoneFn) => {
var input: string = "测试用Promise形式实现的异步方法" ;
var timeout= 2000 ;
var expected: string = `data= ${ input} , timeout= ${ timeout} ` ;
var output: string = '' ;
var promise = service. getDataAsyncByPromise ( input, timeout) ;
promise. then ( ( out: string ) => {
output = out;
expect ( output) . toBe ( expected) ;
done ( ) ;
} ) ;
} ) ;
it ( ' test async by Rxjs' , ( done: DoneFn) => {
var input: string = "测试用Rxjs形式实现的异步方法" ;
var timeout= 3000 ;
var expected: string = `data= ${ input} , timeout= ${ timeout} ` ;
var output: string = '' ;
var rxjsObservable = service. getDataAsyncByRxjs ( input, timeout) ;
rxjsObservable. subscribe ( ( out: string ) => {
output = out;
expect ( output) . toBe ( expected) ;
done ( ) ;
} ) ;
} ) ;
} ) ;