为什么在我的测试中ngForm“控制”属性是空的? (角)

时间:2017-10-16 12:06:39

标签: javascript angular unit-testing angular2-forms angular2-testing

我有一个采用模板驱动形式的组件

<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在测试环境中为空?

1 个答案:

答案 0 :(得分:6)

java.lang.NoClassDefFoundError: com/google/common/primitives/Ints 为&#34;空的原因&#34;在测试环境中,控件没有被初始化&#34;然而&#34;在调用controls时的测试环境中。

我已准备好Plunkr请参阅onSearchCorpus文件)来演示此问题。在同一个文件中,还有一个可行的解决方案。

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

所以而不是:

fakeAsync

你应该写一个像以下的测试:

  it('testing form the wrong way', () => {

    fixture.detectChanges();

    comp.onSubmit(); // Validates and submits a form

    expect(comp.submitted).toEqual(false);
  });