Updating input html field from within an Angular 2 test

前端 未结 3 457
独厮守ぢ
独厮守ぢ 2020-12-02 16:51

I would like to change the value of an input field from within an Angular 2 unit test.



        
3条回答
  •  生来不讨喜
    2020-12-02 17:49

    You're right that you can't just set the input, you also need to dispatch the 'input' event. Here is a function I wrote earlier this evening to input text:

    function sendInput(text: string) {
      inputElement.value = text;
      inputElement.dispatchEvent(new Event('input'));
      fixture.detectChanges();
      return fixture.whenStable();
    }
    

    Here fixture is the ComponentFixture and inputElement is the relevant HTTPInputElement from the fixture's nativeElement. This returns a promise, so you'll probably have to resolve it sendInput('whatever').then(...).

    In context: https://github.com/textbook/known-for-web/blob/52c8aec4c2699c2f146a33c07786e1e32891c8b6/src/app/actor/actor.component.spec.ts#L134


    Update:

    We had some issues getting this to work in Angular 2.1, it didn't like creating a new Event(...), so instead we did:

    import { dispatchEvent } from '@angular/platform-browser/testing/browser-util';
    
    ...
    
    function sendInput(text: string) {
      inputElement.value = text;
      dispatchEvent(fixture.nativeElement, 'input');
      fixture.detectChanges();
      return fixture.whenStable();
    }
    

提交回复
热议问题