I am finding it challenging to create a successful test case for the code snippet below.
In my component.ts file
id = 123456;
data = [];
constructor(private serv: ApiService){}
ngOnInint(){
getData(id);
}
getData(id){
this.serv.getRequest(url+id).subscribe({
(res){
this.data = res;
});
}
In my spec.ts file
describe('component', () =>{
let component: DataComponent,
let fixture: ComponentFixture<OpenCasesComponent>;
let serv: ApiService;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports:[HttpClientTestingModule],
declartions:[DataComponent],
Providers: [ApiService]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.CreateComponent(DataComponent);
component = fixture.componentInstance;
apiService = TestBed.inject(ApiService);
fixture.detectChanges();
});
it('should make api call on load', fakeAsync(()=>{
component.id = '123456';
let fakeResponse = {
name: 'John';
}
component.ngOnInit();
fixture.detectChanges();
spyOn(component, 'getData').withArgs('123456').and.callThrough();
spyOn(apiService, 'getRequest')..and.returnValue(of(fakeResponse));
fixture.detectChanges();
tick();
expect(component.getData).toHaveBeenCalled();
expect(apiService.getRequest).toHaveBeenCalled();
expect(component.data).toContain(fakeResponse);
}));
}
A similar function call works with code somewhat alike. The only difference is that the function is triggered by a button click. I suspect I am not invoking the function here, if so How do I do it.
Can someone point out what I might be doing incorrectly?