Karma Debug Runner for unit tests renders Ionic page incorrectly


#1

Dear all,

I am creating unit tests for my Ionic application using Karma & Jasmine. When I run the unit tests, the Karma debug runner renders a different DOM-tree than when I launch the application with “ionic serve”.

I want to test whether a button is disabled when the page loads. When I preview the app, it is. Within the Karma debug runner, it is NOT.

Does anyone know of a way to run unit tests against the DOM as it is rendered when you launch the app in a normal browser?

The relevant HTML looks like this:

      <form (ngSubmit)="login(loginForm)" #loginForm="ngForm">
        <ion-input type="text" name="username" [(ngModel)]="gebruikersnaam" required> </ion-input>
        <ion-input type="password" name="password" ngModel required></ion-input>
        <button ion-button type="submit" [disabled]="!loginForm.valid">Log in</button>
      </form>

This is what I am trying to test:

it('should disable the login button if no credentials are provided', () => {
        fixture.detectChanges(); 
        debugElement = fixture.debugElement.query(By.css('button'));
        let nativeButton: HTMLButtonElement = debugElement.nativeElement
        expect(nativeButton.hasAttribute('disabled')).toBeTruthy();
    });

Thanks in advance for any advice/guidance!!


#2

If anyone comes across the same issue, be sure to consult this blog first: https://blog.angular-university.io/introduction-to-angular-2-forms-template-driven-vs-model-driven/

Template-driven Angular forms cannot be unit-tested, reactive Angular forms can. Using a reactive rather than a template-driven form solved the problem for me as the Karma debug runner rendered the form as I had expected.