【问题标题】:Angular NgModel two-way binding unit testAngular NgModel 双向绑定单元测试
【发布时间】:2017-08-28 05:25:02
【问题描述】:

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

当输入字段更新时,我想运行一个测试,确保 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");
  }));
});

如果有更好的方法,我当然很高兴收到任何反馈。

【问题讨论】:

    标签: unit-testing angular jasmine karma-jasmine angular-ngmodel


    【解决方案1】:

    你必须跑

    fixture.detectChanges();
    

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

    setUpControl函数

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

    Plunker Example

    另见

    【讨论】:

    • 非常感谢,yurzui!一如既往的赞赏。也感谢 Plunker 的例子。
    • 什么是control
    猜你喜欢
    • 2020-09-12
    • 2017-04-29
    • 2019-01-02
    • 2016-10-12
    • 1970-01-01
    • 2017-10-20
    • 2015-10-15
    相关资源
    最近更新 更多