Attempting to implement unit testing for a service using httpmock has been challenging. The service in question utilizes a method to make http get calls, but I have encountered difficulties in writing the test cases.
saveservice.service.ts -- file
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
const envURL = sessionStorage.getItem('apiBaseURL');
httpGet<T>(url) {
const URL = envURL + url;
return this.http.get<T>(URL, httpOptions);
}
The saveservice.service file contains the httpGET() method, which is utilized by work.service.ts.
work.service.ts
import {SaveserviceService } from '../../.././my-service.service';
getworklist(employeeID){
return this.saveservice.httpGet('work/v1/works?employeeid=' + employeeID);
}
This demonstrates the connection between workservice and save service. Now, the challenge lies in writing unit test cases for work.component.ts file with the implementation of httpmock.
For reference, the apiUrl is defined in a separate file called env.ts -- env.ts
export const apivalue= {
apiBaseUrl:"https://example.co/",
};
work.component.ts
ngOnit(){
this.employeeID:this.id;
this.workservice.getworkList(this.employeeID).subscribe(
(data) => {
this.workList = data;
console.log(" ggghfghfgh", this.worklist);
}, (error) => {
console.log(error);}
The above code snippet showcases work.component.ts file for which unit test cases need to be written. Assistance is required to accomplish this task.
work.component.spec.ts
let httpMock: HttpTestingController;
let injector: Injector;
let workservice: WorksService;
let saveservice123: SaveService;
providers: [
Injector,
HttpClient,
HttpClientTestingModule,
saveService,
worksService
],
httpMock = TestBed.get(HttpTestingController);
workservice = TestBed.get(WorksService);
saveservice123 = TestBed.get(SaveService)
fit('getting work detsails indivually', async(() => {
fixture = TestBed.createComponent(worksComponent);
component = fixture.componentInstance;
fixture.detectChanges();
workservice.getworkList(123).subscribe(() =>{});
const request = httpMock.expectOne("work/v1/works?employeeid=")
// expect(request.request.method).toBe('httpGet');
// request.flush(xxxxx);
An error is being thrown:
Error: Expected one matching request for criteria "Match URL: work/v1/works?employeeGuid=", found none.
Assistance is needed on how to properly write unit test cases for this scenario. Attempts using spy have also proven unsuccessful.
const mockdata = { id:1, title: "Hello world", paste: "console.log('Hello world');"}
const spyOnAdd = spyOn(service, "getworkList").and.returnValue(mockdata);