茉莉花-测试一种具有参数功能的方法

时间:2018-07-11 18:40:12

标签: angular ionic2 karma-jasmine

我正在尝试测试一个具有对象和函数作为参数的方法,希望它已被其对象和函数调用,但是即使我传递了一个函数,它也会返回错误。

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

这是我的代码的样子:

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

1 个答案:

答案 0 :(得分:0)

() => {}替换为jasmine.any(Function),如果您不关心特定功能,就会被设置。参见here