I am trying to test a method which does not return nothing. The method calls a service to perform a Http POST. I have mocked my service and set it as a parameter within SpyOn. The second parameter in the SpyOn call is the name of the method that contains the post operation. In this case, the method name is postSkillforMember. When I run ng test, Jasmine spec list failures throws the following error:
Jasmine Spec List | Failures:
AddSkillModalComponent > Testing addSkill() success
Error: <spyOn> : could not find an object to spy upon for postSkillforMember()
What I am doing wrong? This is the method in my component.ts that I want to test:
Method to test:
addSkill(): void {
this.successCallback=(skill: any) => {
this.showAlert = false;
this.activeModal.close(skill);
};
this.errorCallback=(error: any)=>{
this.showAlert=true;
};
const skillFormBody = {
skill: {
"id": this.itemFormGroup.get("skill")?.value.id,
"skill": ""
},
skillLevel: {
"id": this.itemFormGroup.get("skillLevel")?.value.id,
"skillLevel": ""
}
}
this._skillAddService.postSkillforMember(
this.memberId,
skillFormBody,
this.successCallback,
this.errorCallback
);}
My spec ts mocks the service within describe:
describe in add-skill-modal.component.ts:
describe('AddSkillModalComponent', () => {
let component: AddSkillModalComponent;
let fixture: ComponentFixture<AddSkillModalComponent>;
let mockSkillAddService: jasmine.SpyObj<SkillAddService>;}
And, finally, this is the unit test I wrote for my method:
it in add-skill-modal.component.ts:
it('Testing addSkill() success', () => {
spyOn(mockSkillAddService, 'postSkillforMember');
component.addSkill();
expect(component.showAlert).toBeFalsy();
});
I really appreciate your help. Thank you in advance.
Can you show your TestBed.configureTestingModule({
?
Make sure you create a spyObj for SkillAddService
and add it to the providers.
beforeEach(waitForAsync(() => {
// make sure you create this spy object with postSkillforMember public method to be mocked
mockSkillAddService = jasmine.createSpyObj<SkillAddService>('SkillAddService', ['postSkillforMember']);
TestBed.configureTestingModule({
declarations: [...],
// provide the mock instead of the real one
providers: [{ provide: SkillAddService, useValue: mockSkillAddService }],
}).compileComponents();
}));
it('Testing addSkill() success', () => {
// no need to spy anymore
// spyOn(mockSkillAddService, 'postSkillforMember');
component.addSkill();
expect(component.showAlert).toBeFalsy();
// can do:
expect(mockSkillAddService.postSkillforMember).toHaveBeenCalled();
});