Angular 未在测试中设置正确的表单验证 类

Angular not setting correct form validation classes in tests

Angular 在单元测试环境中应用验证 class 似乎存在问题。通过验证 classes,我的意思是 ng-validng-invalid。我使用的 Angular 版本是 8.2.14.

让我们以这个组件为例:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
  <form ngForm>
    <input type="text" required name="firstName" [(ngModel)]="firstName"/>
    <button type="submit">Submit</button>
  </form>
  `
})
export class AppComponent {
  firstName = '';
}

该模板是一个简单的模板驱动表单。如果您在浏览器中呈现它,在任何交互之前,输入将具有以下 class 名称:ng-untouched ng-pristine ng-invalid。这正是我们所期望的:需要输入,值为空字符串,因此无效。

但是,如果我们有以下测试用例:

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule,
        FormsModule
      ],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));

  it('should apply the correct validation classes', () => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();

    fixture.detectChanges();

    fixture.whenStable().then(() => {
      console.log(fixture.nativeElement.querySelector('input'));
    });
  });
});

记录的元素将具有 class 名称:ng-untouched ng-pristine ng-valid。我希望输入在测试浏览器中无效,就像在没有测试配置的情况下呈现一样。

我的问题是为什么验证 classes 有这样的差异,我怎样才能在测试环境中实现正确的验证?

提前致谢!

我认为您需要将 it 规范设为异步,因为其中包含一些异步代码。

还要查看此 issue,您需要在 whenStable 之后使用 fixture.autoDetectChanges() 或 运行 fixture.detectChanges()