Search code examples
angularjasminekarma-jasmine

how to mock an event callback trigger within a jasmine test


My component code has:

function aa() {
this.component.grid = createItem();
this.component.grid.instance.options.addEventListener('eventAbc',() => { 
  this.bbb ();
})
}

function bbb() {
 console.log("dummy func");
}

in component.spec.ts file:

let content;
setup() {

content = jasmine.createSpyObj('content', ['createItem']);
content.createItem.and.callFake(() => {
return { 
grid: {
 instance: {
  options: {
      addEventListener: (event, action) => {}
  }}}}}

it('testing method aa', () => { 
spyOn(component.grid.instance.gridOptions, 'addEventListener').andCallThrough();
spyOn(component, 'bbb').and.callThrough();
component.aa();
expect(component.grid.instance.gridOptions.addEventListener).toHaveBeenCalled();
expect(component.bbb).toHaveBeenCalled();
}

I want to understand how to mock triggering the 'abcEvent' so that the test goes inside the real callback of the event listener and bbb method gets called.


Solution

  • the way I got access to the call back function of the event listener is by:

    let callBack = addEventListener.calls.allArgs()[0][1]; //this gives access to all the arguments passed to the eventListener method
    callBack(); //manually triggered the callback function bbb()