Saranya Garimella
Saranya Garimella

Reputation: 542

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.

Upvotes: 2

Views: 768

Answers (2)

Saranya Garimella
Saranya Garimella

Reputation: 542

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()

Upvotes: 0

AliF50
AliF50

Reputation: 18889

I would call action in the callback so the bbb method gets called.

Something like this:

content.createItem.and.callFake(() => {
return { 
grid: {
 instance: {
  options: {
      addEventListener: (event, action) => {
       // !! add the following line, call action method so when you pass
       // bbb there it will be called
       action();
    }
  }}}}}

Upvotes: 3

Related Questions