Am a newbie in Unit Testing. I started to write Unit Testing for my Ionic 3 Application using Karma and Jasmine. I followed blogs to get the configurations set and successfully tested the initialisation of App component. I also use ionic-mock to have the mocks.
My first page has a http service call which invokes a provider. Below is the call.
this.portalList.getListInformation().then(data => {
this.infolist = data;
});
And in provider :
return new Promise((resolve,reject) => {
this.http.get(url).subscribe(
data => {
const response: any = data;
resolve(response);
},
(error) => {
reject(error);
})
});
And my .spec.ts is here.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Portal } from './portal';
import { IonicModule, Platform, NavController, NavParams} from 'ionic-angular/index';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { PortalList } from '../../providers/PortalList/PortalList';
import { HttpClient, HttpHandler } from '@angular/common/http';
import {
PlatformMock,
AppsMock,
NavParamsMock,
NavMock,
PortalListMock
} from '../../../test-config/mocks-ionic';
describe(' Portal Page', () => {
let de: DebugElement;
let comp: Portal;
let fixture: ComponentFixture<Portal>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Portal],
imports: [
IonicModule.forRoot(Portal)
],
providers: [
Config,HttpClient, HttpHandler
{ provide: App, useClass: AppsMock},
{ provide: Platform, useClass: PlatformMock},
{ provide: NavParams, useClass: NavParamsMock},
{ provide: NavController, useClass: NavMock},
{ provide: PortalList, useClass: PortalListMock}
]
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(Portal);
comp = fixture.componentInstance;
de = fixture.debugElement.query(By.css('label'));
});
it('should create component', () => expect(comp).toBeDefined());
});
I provided the Mock for the provider.
export class PortalListMock {
public infoList = [{name: "MAC", region: "West"}];
public _getPortal(): any { return {} };
public getListInformation() { return this.infoList; }
return;
}
On executing **npm test**
, it gives error like **this.portalList.getListInformation().then is not a function**
.
How to mock the promise of the provider http request. or how to overcome from this issue.
I believe this is related to you returning an array, instead of a Promise.
I would suggest the following change in the mock provider:
this:
public getListInformation() { return this.infoList; }
to become this:
public getListInformation() { return Promise.resolve(this.infoList); }
That way you return the resolved promise, which is equivalent to the code inside the real provider:
return new Promise((resolve,reject) => {
but restricted to return the resolved Promise always including the static data.