Testing: blur emulate
Asked Answered
B

2

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();
  }))
}
Byproduct answered 21/6, 2017 at 16:30 Comment(0)
G
12

You can use dispatchEvent to emulate a blur:

inp.dispatchEvent(new Event('blur'));
Gog answered 2/10, 2018 at 15:38 Comment(0)
B
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));
}
Bernardinabernardine answered 23/6, 2017 at 2:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.