gpt4 book ai didi

angular - 在angular2中模拟或覆盖扩展类

转载 作者:太空狗 更新时间:2023-10-29 19:28:36 25 4
gpt4 key购买 nike

大家好,我在 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 }

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

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

关于angular - 在angular2中模拟或覆盖扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45374847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com