How can i simulate browser focus when testing using angular and jasmine?

前端 未结 1 1508
天命终不由人
天命终不由人 2021-01-02 10:32

I am trying to write a unit test that checks whether or not the effect of a focus event takes place. My actual test case is more complicated, but I have created a minimal re

1条回答
  •  [愿得一人]
    2021-01-02 10:42

    To trigger an event on an Angular element, you can use the built-in JavaScript ES6 method dispatchEvent with a subsequent call of Angular's change detection mechanism to get your DOM updated:

    inputElement.dispatchEvent(new Event('focus'));
    fixture.detectChanges();
    

    A more elegant way to achieve the same thing is to use angular's wrapper method:

    import { dispatchEvent } from '@angular/platform-browser/testing/src/browser_util'
    
    dispatchEvent(inputElement, 'focus');
    fixture.detectChanges();
    

    An interesting one is when you want to set a value to your input element. You will need to first assign a string to the input's value property and then trigger an 'input' change event:

    inputElement.value = 'abcd';
    dispatchEvent(inputElement, 'input');
    fixture.detectChanges();
    

    Note: There are events that do not act the way you may expect. For example, dispatching a 'click' event will NOT give the focus to your input element! A workaround could be to first trigger a 'focus' event and then a 'click' event as follows:

    dispatchEvent(inputElement, 'focus');
    dispatchEvent(inputElement, 'input');
    fixture.detectChanges();
    

    All the available JavaScript events are here.

    0 讨论(0)
提交回复
热议问题