首页 > 解决方案 > Angular 7:ngModel 数据绑定不会在单元测试中更新组件属性

问题描述

我有一个 Angular 7 组件,searchTerm它的模板中有一个属性和一个输入元素。属性的值通过以下方式绑定到输入元素的值[(ngModel)]="searchTerm"

@Component({
  selector: 'app-search',
  template: `
    <form class="search-form">
      <mat-form-field class="search-form-field">
        <input matInput
               type="text"
               id="search-input"
               [(ngModel)]="searchTerm"
               name="search-input">
      </mat-form-field>
    </form>
  `,
  styleUrls: ['./search.component.scss']
})
export class SearchComponent {
  searchTerm: string;
}

在我的单元测试中,我尝试测试属性是否更改为输入元素的值:

it('should update searchTerm according to the input-value', async (() => {
    fixture = TestBed.createComponent(SearchComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

    const input = fixture.debugElement
                  .query(By.css('#search-input')).nativeElement;
    input.value = 'test-value';
    input.dispatchEvent(new Event('input'));
    fixture.detectChanges();

    fixture.whenStable().then(() =>
      expect(component.searchTerm).toEqual('test-value')
    );
  }));

但是,我得到的只是以下错误消息:

预期未定义等于“测试值”。

有趣的是,当我在浏览器中手动尝试时,绑定完全有效。另外,我已经尝试在我的测试函数中使用fakeAsync而不是,async但它没有任何区别。

我究竟做错了什么?

标签: angularjasminekarma-runner

解决方案


推荐阅读