测试:模糊模拟

时间:2017-06-21 16:30:28

标签: angular jasmine karma-jasmine angular2-testing

我想用输入测试简单的角度分量。

因此,底部的示例几乎没有为测试做准备,并且在组件中应该发生test功能模糊,显示日志,但我在控制台中没有日志。我尝试了两种情况:获取div native元素并单击它并使用blur()函数作为输入本机元素。在角度app模糊成功发生,但它在测试中不起作用。我该如何解决?

@Component({
  template: '<div><input [(ngModel)]="str" (blur)="testFunc($event)" /></div>'
})

class TestHostComponent {
  it: string = '';

  testFunc = () => {
    console.log('blur!!!');
  }
}

describe('blur test', () => {
  let component: TestHostComponent;
  let fixture: ComponentFixture<TestHostComponent>;
  let de: DebugElement;
  let inputEl: DebugElement;

  beforeEach(() => { /* component configuration, imports... */ }

  beforeEach(() => {
    fixture = TestBed.createComponent(TestHostComponent);
    component = fixture.componentInstance;
    de = fixture.debugElement;
    inputEl = fixture.debugElement.query(By.css('input'));
    fixture.detectChanges();
  })

  it('test', async(() => {
    const inp = inputEl.nativeElement;
    inp.value = 123;
    inp.dispatchEvent(new Event('input'));
    fixture.detectChanges();
    expect(component.it).toEqual('123');
    inp.blur();
    const divEl = fixture.debugElement.query(By.css('div'));
    divEl.nativeElement.click();
  }))
}

1 个答案:

答案 0 :(得分:2)

您可以使用dispatchEvent来模拟模糊效果:

inp.dispatchEvent(new Event('blur'));