Caike Motta
Caike Motta

Reputation: 193

Jasmine - Test a method which has a function as Parameter

I am trying to test a method which has an Object and a Function as a parameter, expecting it to have been called with its Object and a Function, but even though I pass a function, it returns an error.

Expected spy openContactEdit to have been called with [ Object({ ... }),
  Function ] but actual calls were [ Object({ ... }), Function ].

This is how my code looks like:

contact-edit.test.ts

class ModalControllerMock {
  static create(page: any, data?: any) {
    return new ModalMock;
  }
}

class ModalServiceMock {
  openContactEdit(contact: any, onDismiss: (data) => any): any {
    let modal = ModalControllerMock.create('EditContactPage', {
      contact: contact
    })

    modal.present();

    let data: any;

    onDismiss(data);
  }
}

it('should open edit contact page', () => {
  const contact = {
    "username": "callain0",
    "name": "Cordelia Allain"
  }
  spyOn(modalService, 'openContactEdit').and.callThrough();

  comp.editContact(contact)

  expect(modalService.openContactEdit).toHaveBeenCalledWith(contact, () => { });
});

modal-service.ts

openContactEdit(contact: any, onDismiss: (data) => any) {
  let modal = this.modalCtrl.create('EditContactPage', {
    contact: contact
  })

  modal.onDidDismiss(data => {
    onDismiss(data);
  })

  modal.present();
}

Upvotes: 1

Views: 5485

Answers (1)

Raja
Raja

Reputation: 90

Replace your () => {} with jasmine.any(Function) and you'll be set if you don't care about the specific function. See here.

Upvotes: 3

Related Questions