我在基于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';
}

和测试 . 这两个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');
   });

});

有没有人看到如何解决这个问题,以便它能正常工作?我环顾四周,找不到任何错误报告,解释为什么没有表格会有效但却失败了 .