Unit testing with private service injected using jasmine angular2
You don't spy on the service tied to your TestBed. Get the service from your Testbed
beforeEach(() => { TestBed.configureTestingModule({ providers: [ServiceToTest , { provide: ServiceInjected, useValue: serviceInjectedStub }] }); injectedService = TestBed.get(ServiceInjected);});
And test on it
spyOn(injectedService, 'configure').and.returnValue(/* return same data type here */);// ...expect(injectedService.configure).toHaveBeenCalled();
Or you can use jasmine.createSpyObj
and provide it with useValue
like bellow:
describe('YourComponent', () => { let serviceInjectedSpy: jasmine.SpyObj<ServiceInjected>; beforeEach(async(() => { // notice here serviceInjectedSpy = jasmine.createSpyObj('ServiceInjected', ['configure']); TestBed.configureTestingModule({ declarations: [YourComponent], providers: [ {provide: ServiceInjected, useValue: serviceInjectedSpy} ], imports: [ ... ] }).compileComponents().then(() => { fixture = TestBed.createComponent(YourComponent); component = fixture.componentInstance; }); }); it('should assert my test', () => { serviceInjectedSpy.configure.and.returnValue(/* what you want */); component.init(); expect(serviceInjectedSpy.configure).toHaveBeenCalled(); });});
Use this:
spyOn(serviceInjectedStub, 'configure').and.returnValue(config); // config is a mock