How would I simply test that my service is called?
myComp.ts
constructor(private myService: MyService) {}
myFunction() {
this.myService.someFunction();
}
myTest.ts
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, HttpClientModule],
declarations: [MyComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should delete customer feed', () => {
const mySpy = spyOn(MyService, 'someFunction');
component.myFunction();
expect(mySpy).toHaveBeenCalledTimes(1);
});
Currently the line const mySpy = spyOn(MyService, 'someFunction'); shows red squigglies on 'someFunction' stating:
Argument of type 'someFunction' is not assignable to parameter of type prototype | service | url
Update How my set up is now as per comments:
let myService: MyService;
beforeEach(() => {
...
providers: [MyService],
...
.compileComponents()
});
beforeEach(() => {
fixture = TesBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
myService = TestBed.get(MyService);
});
Update (solution) I was still using the UPPERCASE MyService rather than the lowercase myService in my spy definition!
You can simply go ahead and spyOn your service method to see if it was called.
You should mock the service and provide it to your component at the TestBedConfiguration.
You can mock all your service methods and return any value as needed to check if call was made to your service method.
class MyServiceStub {
constructor(){}
myFunction() { returns Observable.of({});}
}
let myService;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule, HttpClientModule],
providers: [
{ provide: MyService, useValue: new MyServiceStub() }
],
schemas: [NO_ERRORS_SCHEMA]
declarations: [MyComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
myService = TestBed.get(MyService);
});
it('should delete customer feed', () => {
const mySpy = spyOn(myService , 'someFunction');
component.myFunction();
expect(mySpy).toHaveBeenCalledTimes(1);
});
if you do not want to mock your service using a stub , just use TestBed.get(MyService) to get the service instance after you provide the service to your component in TestBed.configureTestingModule
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