I am trying to test my Angular service using Karma-Jasmine and I need to be sure that after service is initialized loadApp
function have been called. What is the best way to test it?
import { Injectable, NgZone } from '@angular/core';
@Injectable()
export class GdlService {
appName = 'myAppName';
constructor(
private ngZone: NgZone,
) {
this.ngZone = ngZone;
this.loadApp(this.appName);
}
private loadApp(appName) {
this.ngZone.runOutsideAngular(() => {
// ...some logic
});
}
}
It can be tested as any other function. Considering that loadApp
is prototype method, it can be stubbed or spied on class prototype:
it('', () => {
spyOn(<any>GdlService.prototype, 'loadApp');
const gdl = TestBed.get(GdlService);
expect(gdl['loadApp']).toHaveBeenCalledWith('myAppName');
});
Try mocking the injection for ngZone (I like ts-mockito for this sort of stuff) and then checking to see if ngZone.outsideOfAngular has been called. Due to the nature of typescript, I don't think you'll be able to directly spy on anything that is private comfortably.
Something like this in the test file:
import { GdlService } from 'place';
import { NgZone } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import {
anything,
instance,
mock,
verify
} from 'ts-mockito';
describe('yada yada', () => {
const mockNgZone = mock(NgZone);
// Can use when(mockNgZone.whatever)... to mock what you need
beforeEach(() => {
TestBed.configureTestModule({
providers: [{
provide: NgZone,
useValue: instance(mockNgZone)
}]
});
});
it('checks on loadApp', () => {
verify(mockNgZone.runOutsideAngular(anything())).called();
});
});
If you would prefer to just use the spyOn method instead, you can just replace the object in the useValue portion of the provider.
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