Hello every body i have some problems with angular2 unit tests. Can anybody help me?
I have some class like this
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);
});
});
}
}
How can do mock of ApiService.post() function?
My spec file look like this
describe('PostcodeApiService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
PostcodeApiService,
Http,
ConnectionBackend,
AuthService,
UserService
],
imports: [
HttpModule
]
});
});
it('should ...', inject([PostcodeApiService], (service: PostcodeApiService) => {
// How ovveride post method ?
}));
});
I would be grateful if you could help me with this thing. Thanks for attention!
Create a mock class:
class PostcodeApiServiceMock extends PostcodeApiService {
post(url, payload: any) {
// do something
}
}
and provide it with
{ provide: PostcodeApiServce, useClass: PostcodeApiServiceMock }
You can find a good example here:
https://angular.io/guide/testing#test-a-routed-component
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With