2017-07-28 48 views
3

你好,我每个身体都有一些angular2单元测试的问题。有谁能够帮助我?
我有一些类这样
在angular2中模拟或覆盖扩展类

export class PostcodeApiService extends ApiService { 
 

 
    constructor(Http: Http, auth: AuthService) { 
 
    super(Http, auth); 
 
    } 
 
    
 
    getPostcodes(filterObject) { 
 
    return super.post('postcodes/filter', filterObject); 
 
    } 
 
}

export class ApiService { 
 

 

 
    constructor(private http: Http) { 
 
    } 
 

 
    post(url, payload: any) { 
 
    return new Observable((observer) => { 
 
     this.http.post(`someUrl/${url}`, payload) 
 
      .map((res: Response) => res.json()) 
 
      .catch((error: any) => { 
 
      return Observable.throw(error || `Server error ${url}`); 
 
      }) 
 
      .subscribe((data) => { 
 
      observer.next(data); 
 
      }); 
 
    }); 
 
    } 
 

 

 
}

怎么办ApiService.post的模拟()函数?

我的规格文件看起来像这样

describe('PostcodeApiService',() => { 
 

 

 
    beforeEach(() => { 
 
    TestBed.configureTestingModule({ 
 
     providers: [ 
 
     PostcodeApiService, 
 
     Http, 
 
     ConnectionBackend, 
 
     AuthService, 
 
     UserService 
 
     ], 
 
     imports: [ 
 
     HttpModule 
 
     ] 
 
    }); 
 
    }); 
 

 
    it('should ...', inject([PostcodeApiService], (service: PostcodeApiService) => { 
 
    // How ovveride post method ? 
 
    })); 
 
    
 
    
 
    
 
});

我将不胜感激,如果你能帮助我这个东西。 感谢您的关注!

回答

1

创建一个模拟类:

class PostcodeApiServiceMock extends PostcodeApiService { 
     post(url, payload: any) { 
     // do something 
     } 
    } 

,并为其提供

{ provide: PostcodeApiServce, useClass: PostcodeApiServiceMock } 

您可以在这里找到一个很好的例子:

https://angular.io/guide/testing#test-a-routed-component

+2

不知怎的,这不是为我工作和afaik,你只能以这种方式覆盖injectables(在例子'Http'和'AuthService'中),n ot扩展类:( 有没有办法完全交换服务的超类(又名原型)进行测试? – shoesel