【发布时间】:2018-03-27 22:52:48
【问题描述】:
我有一个使用模板驱动表单的组件
<form (ngSubmit)="onSearchCorpus(form)" #form="ngForm">
<combo-box [(ngModel)]="model.corpus" name="corpus" #corpus="ngModel"></combo-box>
<input [(ngModel)]="model.label" name="label" id="label" type="text" required pattern="^(?!\s*$)[\w\_\-\:\s]*" maxlength="50" class="form-control label-name" autocomplete="off" #label="ngModel">
<textarea [(ngModel)]="model.query" name="query" id="query" maxlength="3600" required validateQuerySyntax class="form-control search-query" #query="ngModel" #queryControl
placeholder="Example: ("grantee" OR "grant" OR "sponsor" OR "contribute" OR "contributor") NEAR ("non-profit organization" OR "charities")">
</textarea>
<button [disabled]="corpusValidationInProgress" type="submit" class="button-level-one">Search</button>
</form>
在处理表单提交的方法中,我访问了 NgForm 实例的 controls 属性,它在浏览器中运行良好。
onSearchCorpus(formData: NgForm) {
...
const corpusErrors = formData.controls.corpus.errors;
...
}
但是,当我尝试使用 Karma 测试此方法时,NgForm 的 controls 属性为空。我很困惑为什么会这样。该方法失败,错误为cannot read property "errors" of undefined。
这是我的测试的样子:
it('should not perform corpusSearch if selected corpus no longer exists', () => {
component.ngOnInit();
const form = fixture.debugElement.query(By.css('form'));
form.triggerEventHandler('submit', null);
...
});
这就是我设置测试服的方式:
beforeEach(async(() => {
TestBed.configureTestingModule({
// schemas: [NO_ERRORS_SCHEMA],
imports: [
FormsModule,
PopoverModule
],
providers: [
CorpusSearchService,
{ provide: ApiService, useValue: ApiServiceStub },
{ provide: Router, useClass: RouterStab },
],
declarations: [
SearchCorpusComponent, //<--component under test
ComboBoxComponent //<-- 3rd party combobox which is used for first control
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SearchCorpusComponent);
component = fixture.componentInstance;
apiService = fixture.debugElement.injector.get(ApiService);
subject = new Subject();
});
那么,为什么controls在测试环境中是空的呢?
【问题讨论】:
标签: javascript angular unit-testing angular2-forms angular2-testing