Reputation: 36331
I am trying to add a test to test the following section of code, but I am not sure how, as the output says that lines 60-109
are uncovered. It looks something like this:
public async ngOnInit() {
const data = await this.requestAppService.getData()
this.tableModel = { // Line 60
...this.tableModel,
rows: data.map(
/*
* Map data
*/
)
}
this.subscriptions.push(
/* Add a subscription */
)
// Line 109
}
The test that I am using looks like this:
it('...', fakeAsync(() => {
const spy = spyOn(component, 'ngOnInit').and.callThrough()
component.ngOnInit()
tick()
expect(spy).toHaveBeenCalled()
}))
This was just a guess of how I think I should test it, but it doesn't seem to cover the lines.
I have also tried callFake
, which doesn't work either.
it('...', fakeAsync(() => {
const spy = spyOn(component, 'ngOnInit').and.callFake(() => Promise.resolve())
component.ngOnInit()
tick()
expect(spy).toHaveBeenCalled()
}))
Upvotes: 0
Views: 152
Reputation: 55443
The problem is with spyOn
statement. You are spying on ngOnInit
function. You must spy on the service's getData
function.
Inject & use requestAppService
instance as shown below,
it('...', fakeAsync(() => {
const spy = spyOn(requestAppService, 'getData').and.callThrough()
component.ngOnInit()
tick()
expect(spy).toHaveBeenCalled()
}))
OR
If you want getData
to give you some mock data
or promise
,
it('...', fakeAsync(() => {
const spy = spyOn(requestAppService, 'getData').and.callFake(() => {
return new Promise((resolve) => {
resolve(YOUR_OBJECT);
});
component.ngOnInit()
tick()
expect(spy).toHaveBeenCalled()
}))
Upvotes: 1