I start to learning how to do unit test with Jest and I want to test if the modal is open after I click on submit, but I'm getting the error: Matcher error: received value must be a mock or spy function.
TS
buildform(){
this.form = this.fb.group({
firstName: ['',Validators.required],
secondName:'',
})
}
onSubmit(){
if(this.form.valid){
this.openModal();
}
}
openModal(){
///...
}
spec.ts
it('should open modal if the form is valid', () => {
component.buildform();
component.form.setErrors(null);
fixture.detectChanges();
component.onSubmit();
expect(component.openModal).toHaveBeenCalledWith();
});
CodePudding user response:
The syntax for testing if a function has been called or not look something like this:
it('should open modal if the form is valid', () => {
const openModalSpy = jest.spyOn(component, 'openModal');
component.buildform();
component.form.setErrors(null);
fixture.detectChanges();
component.onSubmit();
expect(openModalSpy).toHaveBeenCalled();
});
This is because, as the error state, for expect(x).toHaveBeenCalled
to work, x
have to be a mock
like jest.fn()
or a spy
like jest.spyOn(obj, 'functionName')