单元测试角度模板驱动形式

时间:2019-08-06 21:19:28

标签: angular typescript ionic-framework

我有一个要测试的简单模板驱动表单。

import {Component, ViewChild} from "@angular/core";
import {NgForm} from "@angular/forms";

@Component({
    templateUrl: "passwordrecover.html"
})
export class PasswordRecoverComponent
{
    @ViewChild(NgForm) ngForm: NgForm;

    private onSubmit(): void
    {
        console.log(this.ngForm.value.email);
    }
}


/* test */
beforeEach(async () => {
    fixture = await TestBed.createComponent(PasswordRecoverComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
});


it("Don't allow form submit if it is not valid", async (() => {

    const template = fixture.nativeElement;
    const loginButton = template.querySelector("#submitButton");
    expect(loginButton.disabled).toBe(true);

    component.ngForm.controls["email"].setValue("test@gmail.com");

    fixture.detectChanges();
    fixture.whenStable().then(() => {
        // THIS ONE IS FAILING !!!!
        expect(loginButton.disabled).toBe(false);
    });


}));
<ion-content padding>
    <form #form="ngForm" (ngSubmit)="onSubmit()">
        <ion-grid>
            <ion-row>
                <ion-col size-sm="6" offset-sm="3">
                    <ion-card>
                        <ion-item margin="20  %">
                            <ion-img [src]="logoPath"></ion-img>
                        </ion-item>

                        <ion-item margin="10%">
                            <ion-label position="floating">E-mail address</ion-label>
                            <ion-input type="email"
                                       name="email"
                                       ngModel
                                       autocomplete
                                       required
                                       email>
                            </ion-input>
                        </ion-item>

                        <ion-button expand="block" type="submit"                  [disabled]="!ngForm.valid" id="submitButton">Login</ion-button>
                        <p>Do not have an account?</p>
                    </ion-card>
                </ion-col>
            </ion-row>
        </ion-grid>
    </form>
</ion-content>

但是我的第二个期望失败了,我不知道为什么我的按钮的disable属性没有在测试中更新!..运行应用程序不是那样的,因为当表单有效时,按钮实际上被启用了。 / p>

我已经用反应式表单尝试了相同的测试方法,并且效果很好,但不适用于模板驱动的表单。

0 个答案:

没有答案