With angular 10, in a signup scenario I have a simple email input that I subscribe to with valueChanges so I check for each input with my authService if the email already exists in the DB; if it does I show a login button that redirects to the login page. The code works fine but I didn't succeed to make the test for this. I found a lot of solutions on the web to test the form valueChanges but none with the nested mock service and observable operator switchMap. Could you help me to find the good way to test this?
my template file with the input and the button:
<input matInput id="email" formControlName="email" type="email">
<button mat-raised-button id="goToLoginButton" (click)="goToLogin()"
*ngIf="showGoToLoginButton">Go to Login</button>
my component file with the valueChanges and switchMap
const emailControl = this.signupForm.get("email");
emailControl.valueChanges
.pipe(
switchMap((emailValue) => {return this.authService.doesEmailExist$(emailValue)}))
.subscribe((emailExist: boolean) => {
if (emailExist) this.showGoToLoginButton = true })
So all this works fine, but I couldn't make the test file correctly:
// in my beforeEach(), here is the mock of authentificationService.doesEmailExist$
// so it always returns an observable that emits true (here I want to test the login button
// appears when the input email exists)
authServiceMock = jasmine.createSpy("AuthService");
authServiceMock.doesEmailExist$ = of(true);
// I provided the mock in the TestBed.configureTestingModule
providers: [
FormBuilder,
AuthService,
{provide: AuthService, useValue: authServiceMock}]
// then my test:
it("should show login button when email exists", () => {
// Checks at first the login button doesn't exist : test ok
let loginButton = fixture.debugElement.query(By.css('button[id="goToLoginButton"]'))
expect(loginButton).toBeFalsy()
// Gets the input email control
const emailControl = component.signupForm.get("email")
// Sets some string in it, but the mock should return true whatever the value is
emailControl.setValue("existing@email.com")
// Emits value in the valueChanges observable (at least I thought it does...)
fixture.detectChanges()
// Checks this.showGoToLoginButton = true with the mock doesEmailExist$
// (already fails at this point)
expect(component.showGoToLoginButton).toBeTruthy();
// Checks the login button appeared
loginButton = fixture.debugElement.query(By.css('button[id="goToLoginButton"]'))
expect(loginButton).toBeTruthy()
})
Could you please tell me the good way to test this?
Aucun commentaire:
Enregistrer un commentaire