mardi 16 mars 2021

Is it possible to trigger (ngModelChange) event on a custom child component in a parent via Jest test?

I'm working on a unit test in Jest for a component. One of the pieces of functionality I want to verify is that when a child component rendered in the component modifies its ngModel binding and triggers the (ngModelChange) event that the parent does the appropriate thing.

For brevity, here's the relevant code of the parent, containing a reference to the child, <child-component>:

<div>I am the parent component</div>
<child-component
  [(ngModel)]="myModel"
  (ngModelChange)="doAThing($event)"
>
</child-component>

In the test I've tried a test like this:

it('Binds to the child properly', () => {
  // Bunch of set up where I use Angular's TestBed utility to get a reference to the component
  // and the testing fixture 

  spyOn(component, 'doAThing');
  component.myModel = 'new data';
  fixture.detectChanges();
  expect(component.doAThing).toHaveBeenCalled();
});

But the spy never detects any calls. Now this kind of makes sense because I'm modifying the model directly on the parent which would pass down to the child but shouldn't come back up to the parent-- you'd end up in a recursive loop in that case.

So then the question is: how do I cause this <child-component> to fire off its (ngModelChange) event within a Jest test for the parent component?

My only thought from reading the documentation is to stub out the child component and somehow get a reference to it and manually cause the event to fire. But that seems like a lot of work. Is there an easier path?

Appreciate any thoughts on how best to test this functionality.

Aucun commentaire:

Enregistrer un commentaire