我有一个简单的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()
的值。
我做错了什么?
答案 0 :(得分:1)