bmd*_*bmd 6 unit-testing jasmine karma-jasmine angular-ngmodel angular
我正在尝试测试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");
  }));
});
如果有更好的方法,我当然很乐意收到有关此问题的任何反馈。
你必须跑
fixture.detectChanges();
在调度事件之前确保您的控件已初始化并注册onChange事件
setUpControl 功能
// view -> model
dir.valueAccessor.registerOnChange(function (newValue) {
    dir.viewToModelUpdate(newValue);
    control.markAsDirty();
    control.setValue(newValue, { emitModelToViewChange: false });
});
也可以看看
| 归档时间: | 
 | 
| 查看次数: | 3889 次 | 
| 最近记录: |