尝试在组件中对基于模板的表单进行单元测试,表单没有控件

Jak*_*rth 5 forms unit-testing angular

我正在尝试在我的组件中对基于模板的表单进行单元测试。该表格很简单,包含一个人的联系信息。我想做的是对各种验证场景进行单元测试。我认为我能做的就是简单地设置一个值,例如电子邮件地址,然后检查 ngForm 对象,获取 emailAddress 的相应 formControl,然后检查有效性状态。然而,我发现该表单虽然存在,但根本不包含任何控件。所以看来这个形式从来没有完全建成。

代码(为了简洁起见,我省略了导入和一些提供程序语句等):

人员详细信息-联系信息.component.html

<custom-input type="text"
            name="emailAddress"
            [(ngModel)]="model.emailAddress"
            maxlength="255"
            pattern="^[^\s@]+@[^\s@]+\.[^\s@]{2,}$"
            #emailAddress="ngModel">
</custom-input>

<custom-input type="text"
            [disabled]="permissions.canViewOnly"
            name="phone"
            [(ngModel)]="model.phone"
            maxlength="16">
</custom-input>

<custom-input type="text"
            [disabled]="permissions.canViewOnly"
            name="model.fax"
            [(ngModel)]="fax"
            maxlength="16">
</custom-input>
Run Code Online (Sandbox Code Playgroud)

人员详细信息-contact-info.component.ts

@Component({
    selector: 'person-details-contact-info',
    templateUrl: 'person-details-contact-info.component.html',
    viewProviders: [{ provide: ControlContainer, useExisting: NgForm }]
})
export class PersonDetailsContactInfoComponent {

    @Input('model')
    model: {
        emailAddress: '',
        phone: '',
        fax: ''
    }
}
Run Code Online (Sandbox Code Playgroud)

** 单元测试代码 **

@Component({
    template: `
        <form #form="ngForm">
            <person-details-contact-info [(model)]="model">
            </person-details-contact-info>
        </form>
    `,
    providers: [ ]
})
export class TestHostComponent {
    model: PersonDetailsContactInfoModel = new PersonDetailsContactInfoModel();

    @ViewChild('form')
    ngForm: NgForm;
}

describe('In the file "person-details-contact-info.component.ts', () => {

    let fixture: ComponentFixture<TestHostComponent>;
    let component: TestHostComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [FormsModule, NoopAnimationsModule],
            declarations: [TestHostComponent, PersonDetailsContactInfoComponent],
            providers: [ ]
        });

        fixture = TestBed.createComponent(TestHostComponent);
        component = fixture.componentInstance;
    });

    it('is has invalid email format', () => {
        component.model.emailAddress = 'an invalid email format.';
        fixture.detectChanges();

        const ctrl = component.ngForm.form.get('emailAddress');
        expect(ctrl.valid).toBe(false);
    });
});
Run Code Online (Sandbox Code Playgroud)

上面的测试是错误的,因为“ctrl”对象为空。表单中不存在 emailAddress 控件。顺便说一句,这一切在实际组件中都工作得很好,所以很明显我在单元测试设置上做错了。

最后,为了理解代码,我的应用程序的方式是将一个非常大的表单分解为单独的组件。所以这个“联系信息”组件是一个更大表单的一部分。这就是为什么我要绑定到模型并在 person-details-contact-info.component 的提供者部分中提供现有的 NgForm。再说一次,应用程序本身的一切都运行得很好,只是我尝试进行单元测试的方式没有按照我预期的方式进行。

Jak*_*rth 6

好吧,我知道发生了什么事。我尝试做的事情将会起作用,但在单元测试的“it”块内,在“fixture.detectChanges()”之后,我需要执行“fixture.whenStable()”。例如:

it('is has invalid email format', () => {
    component.model.emailAddress = 'an invalid email format.';
    fixture.detectChanges();

    fixture.whenStable().then(() => {
        const ctrl = component.ngForm.form.get('emailAddress');
        expect(ctrl.valid).toBe(false);
    });        
});
Run Code Online (Sandbox Code Playgroud)

这很有趣,因为我在实际应用程序中遇到了类似的问题,其中组件显然不是“稳定”的。尝试立即访问(在 OnInit 或 AfterViewInit 中)表单内的 formControl 将导致空对象。