测试原始的角度分量形式不起作用

Chr*_*pie 4 jasmine angular angular-test

我有一个带有输入的表单,并且有一个仅在表单数据更改时才需要启用的按钮。我正在使用原始检查,它在浏览器中都能正常工作,但我在测试它时遇到了麻烦。无论我做什么,无论我设置值多少次,原始检查总是正确的。知道我做错了什么吗?

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>
Run Code Online (Sandbox Code Playgroud)

我的打字稿文件

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
        )
      );
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

还有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
    });
  }));
});
Run Code Online (Sandbox Code Playgroud)

Ash*_*iya 6

这不起作用,因为

如果用户尚未更改 UI 中的值,则控件是原始的。

仅当您使用 UI 更改值时,原始属性才会变为 false。以编程方式设置/更改表单值不会改变它。

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

在这里阅读更多内容。

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

component.form.controls.email.setValue("2");
inputElement.dispatchEvent(new Event('input'));
Run Code Online (Sandbox Code Playgroud)

或者

inputElement.dispatchEvent(new Event('input'));
inputElement.value = '2';
Run Code Online (Sandbox Code Playgroud)