我有一个简单的 Angular 表单,想通过端到端测试对其进行测试。即我想从 UI 驱动测试。我写的测试没有像我预期的那样工作。
零件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-foo',
template: `
<form [formGroup]="form">
<input id="foo" type="text" formControlName="foo">
<button id="submit" type="submit">Submit</button>
</form>`
})
export class FooComponent implements OnInit {
form: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
foo: ['', [Validators.required, Validators.pattern('[0-9]+')]]
});
}
}
考试:
import { FooComponent } from './foo.component';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { ReactiveFormsModule, FormsModule } from "@angular/forms";
import { By } from '@angular/platform-browser';
fdescribe('Foo component', () => {
let component: FooComponent;
let fixture: ComponentFixture<FooComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ReactiveFormsModule, FormsModule],
declarations: [FooComponent]
});
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
component.ngOnInit();
});
it('should have a valid foo when input is valid', () => {
let foo = fixture.debugElement.query(By.css("#foo"));
foo.nativeElement.value = "12345";
fixture.detectChanges();
expect(component.form.controls.foo.valid).toBeTruthy();
});
});
测试失败:Expected false to be truthy.
。尽管我事先进行了调试,但该12345
值并未显示为我调试此部分时的值。component.form.controls.foo.value
fixture.detectChanges()
我究竟做错了什么?