3

I have a form that I am trying to test that has multiple inputs. The inputs save on blur and then the form is validated and checks to see if any of the fields are dirty and it saves.

The problem is that no matter what I try, I can't get the form to appear as dirty in the test. I've tried

element.querySelector('#id').value = 'Text';

and I've tried updating the actual object that the form gets its data from (updating the model I think this is) with no dice.

I saw there was a dispatchEvent method in the angular2 repostiory that allows you to send input to an element, but that is in angular2/testing_internals so it isn't importable in external projects. Any ideas of how I can trick the form into thinking that it is receiving input in the unit test?

On another note, the documentation for ng2 unit testing is really poor when I search on google. Is there any good sites you know of?

tallkid24
  • 1,697
  • 4
  • 16
  • 20

1 Answers1

3

Dispatch an input event from the element after you set the value.

https://plnkr.co/edit/SyYbKLBtsTL645rSUjAS?p=preview

Event though files from src are not public API it contains a convenient

import {dispatchEvent} from 'angular2/testing_internal';

which allows to simply

 dispatchEvent(password, 'input');

See also

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • And you can use http://stackoverflow.com/questions/2381572/how-can-i-trigger-a-javascript-event-click/2381862 to make sure it works in different browsers – Ruan Mendes Mar 01 '16 at 23:25
  • It's that easy? I didn't realize a change event was fired to trigger the dirty of an input. I took all day hitting my head against the wall for this. So when I get the element using element.querySelector('#id'), I can create an onchange event and do element.querySelector('#id').dispatchEvent(event)? – tallkid24 Mar 01 '16 at 23:43
  • "i'm not sure this will work anymore, see: https://github.com/angular/angular/issues/4177, I could not get it to work. – Hello Dave Jul 07 '16 at 22:33