Having trouble with coverage in my Angular/Karma tests.
Recently, I developed a component containing a signUp() function
angularFireAuthSignOutSpyObj acts as a spy for this.auth within the component (Firebase Auth)
signUp() {
if (this.registrationForm.valid) {
this.auth.createUserWithEmailAndPassword
(
this.registrationForm.get('email')?.value,
this.registrationForm.get('password')?.value
)
.then(() => {
this.appMessage = "Account created !";
})
.catch((error) => {
this.appMessage = error.message;
});
} else {
this.appMessage = 'Submit logic bypassed, form invalid !'
}
}
I'm currently conducting Karma tests on this component function as is
it('should submit registration with form values', () => {
spyOn(component, 'signUp').and.callThrough();
angularFireAuthSignOutSpyObj.createUserWithEmailAndPassword.and.returnValue({
then: function () {
return {
catch: function () {
}
};
}
});
component.registrationForm.controls.email.setValue('<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5e2a3b2d2a1e3b333f3732703d3133">[email protected]</a>');
component.registrationForm.controls.password.setValue('ValidPass123');
component.registrationForm.controls.passwordCheck.setValue('ValidPass123');
expect(component.registrationForm.valid).toBeTruthy();
debugElement.query(By.css("button")).triggerEventHandler("click", null);
expect(component.signUp).toHaveBeenCalled();
expect(component.auth.createUserWithEmailAndPassword)
.toHaveBeenCalledWith(
component.registrationForm.controls.email.value,
component.registrationForm.controls.password.value)
// expect(component.appMessage).toEqual('Account created !');
});
The last expect section has been commented out due to an Error: Expected undefined to equal 'Account created !'. The issue arises from the lack of control over the defined then and catch functions in the mocked service angularFireAuthSignOutSpyObj.
In essence, the functions are defined to prevent errors when accessed in the signUp() function. However, I am seeking a way to trigger the then(() => ...) and catch(() => ...) events to properly test if the app message updates correctly.
All testing components work fine until this point. It seems modifying createUserWithEmailAndPassword.and.returnValue might hold the key to triggering the expected functions.
angularFireAuthSignOutSpyObj.createUserWithEmailAndPassword.and.returnValue({
then: function () {
return {
catch: function () {
}
};
}
});
If anyone has suggestions on how to properly test the behaviour of auth.createUserWithEmailAndPassword in my component, I would greatly appreciate it!
Thank you,
David