5

I would like to test simple angular component with input.

So an example in the bottom has little preparation for the test, and in a component should occur test function on blur, which shows log, but I have no logs in console. I tried 2 cases: getting div native element and click it and use blur() function for input native element. In angular app blur successfully occur, but it doesn't work in test. How can I fix it?

@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();
  }))
}
Maciej Treder
  • 11,866
  • 5
  • 51
  • 74
qwe asd
  • 1,598
  • 3
  • 21
  • 31

2 Answers2

12

You can use dispatchEvent to emulate a blur:

inp.dispatchEvent(new Event('blur'));
timray
  • 588
  • 1
  • 9
  • 24
1

Use

dispatchFakeEvent(inp, 'blur');

and here is dispatchFakeEvent:

export function createFakeEvent(type: string) {
 const event = document.createEvent('Event');
 event.initEvent(type, true, true);
 return event;
}

export function dispatchFakeEvent(node: Node | Window, type: string) 
{
  node.dispatchEvent(createFakeEvent(type));
}
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32