Home > Software engineering >  On emit event: Expected a spy, but got Function
On emit event: Expected a spy, but got Function

Time:11-16

I run this test but I get this error:

Unhandled Promise rejection: <toHaveBeenCalledWith> : Expected a spy, but got Function.

  it('should change myComponent value', () => {
     spyOn(component.mychange, 'emit');
     const input = fixture.debugElement.query(By.css('#mychange')).nativeElement;
     input.value = "2";
     fixture.whenStable().then(() => {
       expect(component.mychange.emit).toHaveBeenCalledWith(2);
     });
   });

There are similar questions, but it happens to me on an emit event, I tried the solutions of those questions but they don't work.

CodePudding user response:

See you are setting up a spy on emit method here - spyOn(component.mychange, 'emit');

Problem seems to be with triggering of the change -

so you would need to call component.mychange(10);

So your code would become

it('should change myComponent value', async () => {
     spyOn(component.mychange, 'emit');
     const input = fixture.debugElement.query(By.css('#mychange')).nativeElement;
     input.value = "2";
     component.mychange(2);
     await fixture.whenStable()
     expect(component.mychange.emit).toHaveBeenCalledWith(2);
   });

Please also I have used async await which makes it much better!!

  • Related