Jasmine-jQuery - can you "call through" an event spy?

90 Views Asked by At

I need to duplicate the functionality of a spy that is called through for an event. I.e., given that there exists: spyOn(method).and.callThrough(), does there also exist something like: spyOnEvent(event).and.triggerThrough()?

1

There are 1 best solutions below

1
Daniel ZA On

The event acts similarly as a function call, so you would set it up in the same way.

E.g. when you setup your component, and have a function (onInit) where you expect another function (myFunction) to be called as part of it.

// arrange
spyOn(component, 'myFunction');

// act
component.onInit();

// assert
expect(component.myFunction).toHaveBeenCalled();

In the same way you can thus setup your events, where the event (myEvent) is triggered inside the tested function (myFunction):

  // arrange
  spyOn(component.myEvent, 'emit');

  // act 
  component.myFunction(); 

  // assert
  expect(component.myEvent.emit).toHaveBeenCalled();

Only when you have a service has a call that is expected to execute will you normally setup the data, as your test scope requires some return data:

spyOn(myService, 'myServiceFunction').and.returnValue(of(true));

Alternatively you can set it up as:

mockedService.spyOf(x => x.myServiceFunction).and.returnValue(of(true));