首页 文章

Angular NgModel two-way 绑定单元测试

提问于
浏览
4

我正在尝试测试 Angular 2 中的 two-way 绑定功能。我还阅读了其他一些答案,但我仍然无法通过测试。

当输入字段更新时,我想运行一个测试,确保 AppComponent 类上的 searchQuery 属性与输入字段的值相同。

如上所述,我已经阅读了一些其他答案,因为我已经包含了额外的代码。那么目前可能不需要全部是什么?

零件

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: '<input type="text" name="input" [(ngModel)]="searchQuery" (change)="onChange()" id="search">',
  styles: ['']
})
export class AppComponent {
    public searchQuery: string;

    onChange() {
        console.log(this.searchQuery);
    }

}

单元测试

import { ComponentFixture, TestBed, async, fakeAsync, tick, ComponentFixtureAutoDetect } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

describe('AppComponent', () => {
  let comp: AppComponent;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ AppComponent ],
      providers: [],
      imports: [ FormsModule ],
      schemas: []
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance;
  });

  it('should create the app', fakeAsync(() => {
    const de = fixture.debugElement.query(By.css("#search"));
    const el = de.nativeElement;

    el.value = "My string";

    var event = new Event('input', {
      'bubbles': true,
      'cancelable': true
    });
    el.dispatchEvent(event);

    tick();

    fixture.detectChanges();

    expect(comp.searchQuery).toEqual("My string");
  }));
});

如果有更好的方法,我当然乐意得到任何反馈。

1 回答

  • 3

    你必须跑

    fixture.detectChanges();
    

    在调度事件之前,确保您的控件已初始化并注册了onChange事件

    setUpControl功能

    // view -> model
    dir.valueAccessor.registerOnChange(function (newValue) {
        dir.viewToModelUpdate(newValue);
        control.markAsDirty();
        control.setValue(newValue, { emitModelToViewChange: false });
    });
    

    Plunker 示例

    也可以看看

相关问题