当在表单中使用时,Angular2 单元测试不会更新输入的 ngModel

All*_*len 5 angular2-testing angular

我在基于 Angular 2.4 的应用程序中进行了相当广泛的测试。我们尚未能够测试的一个领域是带有输入的表单。我最终将其归结为一个小测试用例。我有一个显示问题的 plnkr:https://plnkr.co/edit/NyeAoh2Uo5rJT9if6j64 (请参阅 form_bug.spec.ts)

注意:我根据测试指南中的代码的工作方式来构建此示例。

问题是,当我们将输入与 ngModel 连接起来,然后在测试套件中更新输入时,仅当输入不在表单内时,数据才会流入组件。如果我们将其添加到表单中,那么数据将无法正确流动。

代码的核心部分是:

@Component({
   selector: 'with-form-test',
   template: `
   <div>
      <div class="show_val">{{testVal}}</div>
      <form>
         <input name="test_val" id="val_id" [(ngModel)]="testVal" />
      </form>
   </div>
   `,
})
class WithFormTestComp {
   testVal: string = 'start';
}
Run Code Online (Sandbox Code Playgroud)

和测试。其中的两个 Expect() 检查失败。

describe('WithFormTest', () => {
   let fixture: ComponentFixture<WithFormTestComp>;
   let comp:    WithFormTestComp;
   let comp_de: DebugElement;

   function getInput(): DebugElement {
      return comp_de.query(By.css('input'));
   }
   function getShowVal(): DebugElement {
      return comp_de.query(By.css('.show_val'));
   }

   beforeEach(() => {
      TestBed.configureTestingModule({
         imports: [
            FormsModule,
         ],
         declarations: [
            WithFormTestComp,
         ],
      });

      fixture = TestBed.createComponent(WithFormTestComp);
      comp    = fixture.componentInstance;
      comp_de = fixture.debugElement;
   });

   it('should update testVal', () => {
      fixture.detectChanges();
      const input_elt: HTMLInputElement = getInput().nativeElement;

      input_elt.value = 'set_val';
      input_elt.dispatchEvent(newEvent('input'));
      fixture.detectChanges();

      const show_val_elt = getShowVal().nativeElement;

      expect(comp.testVal).toEqual('set_val');
      expect(show_val_elt.textContent).toBe('set_val');
   });

});
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这个问题,以便它能够正常工作?我环顾四周,找不到任何错误报告来解释为什么在没有表单的情况下它可以工作,但在使用表单时却失败了。