简体   繁体   English

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

[英]Angular not setting correct form validation classes in tests

There seems to be an issue with Angular applying validation classes in unit test environment. Angular 在单元测试环境中应用验证类似乎存在问题。 By validation classes I mean ng-valid and ng-invalid .通过验证类,我的意思是ng-validng-invalid The Angular version I use is 8.2.14 .我使用的 Angular 版本是8.2.14

Let's take for example this component:让我们以这个组件为例:

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 = '';
}

The template is a simple template-driven form.模板是一个简单的模板驱动表单。 If you render it in the browser, before any interaction the input will have the following class name: ng-untouched ng-pristine ng-invalid .如果在浏览器中呈现它,在任何交互之前输入将具有以下 class 名称: ng-untouched ng-pristine ng-invalid This is exactly what we expect: the input is required, the value is an empty string, therefore it is not valid.这正是我们所期望的:输入是必需的,值是一个空字符串,因此它是无效的。

However, if we have the following test case:但是,如果我们有以下测试用例:

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'));
    });
  });
});

The logged element will have the class name: ng-untouched ng-pristine ng-valid .记录的元素将具有 class 名称: ng-untouched ng-pristine ng-valid I expect the input to be invalid in the testing browser, just like if it is rendered without the testing config.我希望输入在测试浏览器中无效,就像在没有测试配置的情况下呈现一样。

My question is why is there such difference in the validation classes and how can I achieve correct validation in the testing environment?我的问题是为什么验证类有这样的差异,我怎样才能在测试环境中实现正确的验证?

Thanks in advance!提前致谢!

I think you need to make your it spec async, because it has some async code inside it.我认为你需要it规范异步,因为它里面有一些异步代码。

Also looking at this issue you'd need to use fixture.autoDetectChanges() or run fixture.detectChanges() after whenStable .还要查看这个问题,您需要在 whenStable 之后whenStable fixture.autoDetectChanges()或运行 fixture.detectChanges fixture.detectChanges()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM