【问题标题】:why ngForm "controls" property is empty in my test? (Angular)为什么 ngForm “controls” 属性在我的测试中是空的? (角度)
【发布时间】: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: (&quot;grantee&quot; OR &quot;grant&quot; OR &quot;sponsor&quot; OR &quot;contribute&quot; OR &quot;contributor&quot;) NEAR (&quot;non-profit organization&quot; OR &quot;charities&quot;)">
      </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


    【解决方案1】:

    controls 之所以为“空”,是因为在调用onSearchCorpus 时,测试环境中的控件“尚未”初始化。

    我准备了一个 Plunkr(参见 form.component.spec 文件)来演示这个问题。在同一个文件中还有一个可行的解决方案。

    简而言之,为了完成这项工作,您需要使用fakeAsync 机制。

    所以而不是:

      it('testing form the wrong way', () => {
    
        fixture.detectChanges();
    
        comp.onSubmit(); // Validates and submits a form
    
        expect(comp.submitted).toEqual(false);
      });
    

    你应该写一个像这样的测试:

      it('testing form the proper way', fakeAsync(() => {
    
        // This first detectChanges is necessary to properly set up the form
        fixture.detectChanges();
    
        // Tick needs to be called in order for form controls to be registered properly.
        tick();
    
        comp.onSubmit(); // Validates and submits a form
    
        expect(comp.submitted).toEqual(false);
    
      }));
    

    【讨论】:

    • 如果 Angular 的文档至少有关于需要这样做的耳语,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 2018-05-14
    • 2011-11-07
    • 2013-03-13
    • 1970-01-01
    • 2011-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多