Emily
's guidance steered me in the right direction. I adapted it to suit the needs of my Angular4/Ionic3 project by incorporating ionic-mocks (https://github.com/user/ionic-mocks).
Within my testing "helper" class, I implemented the following logic:
export function createCustomSpy(baseName: string, methodNames: string[]): { [key: string]: jasmine.Spy } {
const obj: any = {}
for (let i: number = 0; i < methodNames.length; i++) {
obj[methodNames[i]] = jasmine.createSpy(baseName, () => {})
}
return obj
}
Subsequently, I utilized it within my test/spec file by injecting the relevant provider like so:
{ provide: AlertController, useFactory: () => AlertControllerMock.instance() },
Due to Jest's lack of compatibility with ionic-mocks, I had to manually transfer the mocks (utilizing createCustomSpy
):
class ToastMock {
public static initiate(): any {
const instance: any = createCustomSpy('Toast', ['present', 'dismiss'])
instance.present.and.returnValue(Promise.resolve())
instance.dismiss.and.returnValue(Promise.resolve())
return instance
}
}
class ToastControllerMock {
public static initiate(toastMock?: ToastMock): any {
const instance: any = createCustomSpy('ToastController', ['create'])
instance.create.and.returnValue(toastMock || ToastMock.initiate())
return instance
}
}