您的问题来自这样一个事实,即您没有按顺序做事,也不依赖框架来进行测试。
I made a sandbox
有了一个有效的测试,您可以随意查看它。现在进行解释:
让我们从组件开始:
@Component({
selector: 'hello',
template: `
<form #myForm="ngForm">
<input type="text" maxlength="20" name="patient" id="patient" [(ngModel)]="patient">
</form>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@ViewChild('myForm') myForm: NgForm;
patient: string;
}
一个非常简单的组件,具有模板驱动的表单和基本的验证和绑定。
如果你这样做
ngOnInit() {
console.log(this.myForm.controls);
setTimeout(() => console.log(this.myForm.controls));
}
你会看到两者
undefined
和
{ patient: FormControl }
。发生这种情况的原因是,在执行测试之前,您没有等待视图初始化。这意味着测试找不到表单控件,因此无法通过。
现在是测试本身:
import { Component } from '@angular/core';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { HelloComponent } from './hello.component';
import { FormsModule } from '@angular/forms';
describe('HelloComponent', () => {
let fixture: ComponentFixture<HelloComponent>;
let component: HelloComponent;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [HelloComponent]
});
fixture = TestBed.createComponent(HelloComponent);
component = fixture.debugElement.children[0].componentInstance;
fixture.detectChanges();
});
it('should be invalid with more than 20 chars', async(() => {
setTimeout(() => {
component.myForm.controls['patient'].setValue('ddddddddddddddddddddd'); // 21
fixture.detectChanges();
expect(component.myForm.control.invalid).toEqual(true);
});
}));
});
启动非常基本,配置了测试台并检测到更改。
现在是测试的部分:首先必须等待组件加载超时,然后需要使用框架在表单上设置值:
component.myForm.controls['patient'].setValue('ddddddddddddddddddddd'); // 21
此输入21
d
输入,这使其无效。之后,您需要触发更改检测,现在您可以使用
expect(component.myForm.control.invalid).toEqual(true);
这将表单作为控件,这意味着它具有FormControl所具有的所有属性和功能。其中,您可以找到
invalid
属性,该属性说明控件是否处于无效状态。
我必须再次声明,这种测试是无用的,因为您基本上是想看看框架是否正常工作。那不是你的工作,那是棱角球队的工作。如果要测试某个内容,应该测试表单是否在其状态无效时无法提交,这是一条业务规则(我猜),可以防止副作用(与此测试不同)。