How to simulate ionBlur in tests

Viewed 232

Maybe I'll start with what I want to achieve: I have a form with a required field. By default it should not display any error. The error should be displayed if a user touches the field. So my field looks more or less like this:

<ion-input .... (ionBlur)="updateDispayedErrors()"></ion-input>

But I don't know how to test it because:

  1. Running fixture.debugElement.nativeElement.blur() does not triggers ionBlur handler (the same with ....dispatchEvent(new Event('blur')))
  2. Plain angular (blur) does not work (i.e. if I change the code to (blur)="updateDisplayErrors()" then it does not work)
  3. It seems that calling blur() method on native <input .../> element that is created in the browser would work but... the problem is that when I run the tests fixture.debugElement.nativeElement.childNodes is empty... So the native <input .../> is not created

Please let me know if you would like to see a full example to illustrate it.

1 Answers

If you add a selector to ion-input like:

<ion-input .... (ionBlur)="updateDisplayedErrors()" id="specialInput"></ion-input>

Then you can use fixture.debugElement.triggerEventHandler:

import { By } from '@angular/platform-browser';

...

it('should emit ionBlur', () => {
    const ionDe = fixture.debugElement.query(By.css('#specialInput'));
    const ionBlurResult = spyOn(component, 'updateDisplayedErrors');
    ionDe.triggerEventHandler('ionBlur', {});
    expect(ionBlurResult).toHaveBeenCalled();
});
Related