I'm having a service method and it has a service call (HTTP call) and it subscribes immediately and based on the response code it executes the rest of the action command.
Example: Service Method
processData(id): void {
const url = `http://localhost:5000/data/${id}`;
this.http.head(url).subscribe(() => {
console.log('Success');
// Rest of the code - TODO
}, (error) => {
console.log('Failed');
// Rest of the code - TODO
});
}
I tried the following sample (Test case)
fdescribe('ReportedFileService', () => {
let service: DataService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports:[HttpClientModule, HttpClientTestingModule],
providers:[DataService]
});
service = TestBed.get(DataService);
httpMock = TestBed.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
fit('should be valid', () => {
const id = 1;
const filePath = `http://localhost:5000/data/${id}`;
const req = httpMock.expectOne(filePath);
expect(req.request.method).toEqual('Head');
const response = service.processData(id);
})
}
kindly assist me how to handle this situation.
Your service shouldn't be subscribing to the HttpClient observable and thus, it shouldn't be a void return type method. Services should be returning a HttpClient observable to be subscribed to.
E.g.
Service Method
Your service method shouldn't be subscribing to the HTTP call. Invoking .subscribe() will cause the HTTP request to be made.
Component using this service will first inject the service in the constructor. Then, you will subscribe to the service call in the component.
SomeComponent.ts
Your test case should then subscribe to the service just like a component.
service.spec.ts - your service test case
Also, you shouldn't be calling localhost, when you have to deploy this app into a web server, you'd then have to manually change each string.
Instead you should be setting your API urls in the environments file, which is located in:
src/environments/environment.prod.ts
- contains actual domain. E.g. https://example.com/api/data/src/environments/environment.ts
- contains localhost, local development server E.g. http://localhost:5000/data/${id}You'd then import the environment urls as strings in such a manner:
Here are some guides which had helped me and I had bookmarked: Using angular's HttpClient module to send HTTP requests: https://www.techiediaries.com/angular-httpclient/
Testing services: https://www.ng-conf.org/2019/angulars-httpclient-testing-depth/