大家好,我在 angular2 单元测试方面遇到了一些问题。有谁能够帮我?
我有这样的类(class)
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 ?
}));
});
如果你能帮我解决这个问题,我将不胜感激。 感谢关注!
最佳答案
创建模拟类:
class PostcodeApiServiceMock extends PostcodeApiService {
post(url, payload: any) {
// do something
}
}
并提供
{ provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }
你可以在这里找到一个很好的例子:
关于angular - 在angular2中模拟或覆盖扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45374847/