测试 pristine 的 angular 组件形式不起作用

Testing angular component form for pristine is not working

我有一个包含输入的表单和一个仅在表单数据更改时才需要启用的按钮。我正在使用原始检查,它在浏览器中都可以正常工作,但我无法对其进行测试。无论我做什么,无论我设置了多少次值,原始检查总是正确的。知道我做错了什么吗?

HTML 有 2 个带标签的输入和一个按钮

<form (ngSubmit)="login()"
      [formGroup]="form">
  <label>Email</label>
  <input type="email" formControlName="email" name="email">
  <label>Password</label>
  <input type="password" formControlName="password">
  <button type="submit">Login</button>
</form>

我的打字稿文件

import {Component, EventEmitter, OnInit, Output} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";

export class User {
  constructor(public email: string,
              public password: string) {
  }
}

@Component({
  selector: 'app-login-component',
  templateUrl: './login-component.component.html',
  styleUrls: ['./login-component.component.scss']
})
export class LoginComponentComponent implements OnInit {
  @Output() loggedIn = new EventEmitter<User>();
  form: FormGroup;

  constructor(private fb: FormBuilder) {
  }

  ngOnInit() {
    this.form = this.fb.group({
      email: ['', [Validators.required, Validators.pattern("[^ @]*@[^ @]*")]],
      password: ['', [Validators.required, Validators.minLength(8)]],
    });
  }

  login() {
    console.log(`Login ${this.form.value}`);
    if (this.form.valid) {
      this.loggedIn.emit(
        new User(
          this.form.value.email,
          this.form.value.password
        )
      );
    }
  }
}

还有 2 个测试。我尝试过异步测试和没有。我还尝试设置本机元素和表单的值。但在这两种情况下,原始检查始终为真。知道我做错了什么吗?

import {async, ComponentFixture, TestBed} from '@angular/core/testing';

import {LoginComponentComponent} from './login-component.component';
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {By} from "@angular/platform-browser";

describe('Component: Login', () => {

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

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule, FormsModule],
      declarations: [LoginComponentComponent]
    });
    fixture = TestBed.createComponent(LoginComponentComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
  });

  it('Tried WIHTOUT async function', () => {
    expect(component.form.pristine).toBeTrue();         //Should not be in a modified state when it starts
    fixture.detectChanges();

    const inputElement = fixture.debugElement.query(By.css('input[name="email"]')).nativeElement;
    //Try to set the control itself and the form
    component.form.controls.email.setValue("2")
    inputElement.value = '2';

    //Detect changes and wait to be stable
    fixture.detectChanges();
    expect(inputElement.value).toEqual("2");  //Test that the value has infact change
    expect(component.form.pristine).toBeFalse();   //This fails
  });

  it('Tried using async function', async(() => {
    expect(component.form.pristine).toBeTrue();         //Should not be in a modified state when it starts
    fixture.detectChanges();

    const inputElement = fixture.debugElement.query(By.css('input[name="email"]')).nativeElement;
    //Try to set the control itself and the form
    component.form.controls.email.setValue("2")
    inputElement.value = '2';

    //Detect changes and wait to be stable
    fixture.detectChanges();
    fixture.whenStable().then(() => {
      expect(inputElement.value).toEqual("2");  //Test that the value has infact change
      expect(component.form.pristine).toBeFalse(); //This fails
    });
  }));
});

这不起作用,因为

A control is pristine if the user has not yet changed the value in the UI.

只有当您使用 UI 更改值时,原始的 属性 才会变为 false。 Setting/changing 以编程方式形成的值不会改变它。

解决此问题的一种方法是,在您的测试中,您可以使用 component.form.markAsDirty() 使原始错误并使测试正常工作。

Read more here.

另一种方法是模拟行为,就好像值从 UI 改变了一样,您可以使用

component.form.controls.email.setValue("2");
inputElement.dispatchEvent(new Event('input'));

inputElement.dispatchEvent(new Event('input'));
inputElement.value = '2';