![](/img/trans.png)
[英]Karma/Jasmine testing Ionic 6 - NullInjectorError: No provider for Geolocation
[英]Mock a provider class to return response and handle promise - Unit Testing with Jasmine and Karma with Ionic 3
是單元測試的新手。 我開始使用Karma和Jasmine為Ionic 3應用程序編寫單元測試。 我關注了博客以獲取配置設置,並成功測試了App組件的初始化。 我也使用ionic-mock進行模擬 。
我的第一頁有一個調用提供程序的http服務調用。 下面是電話。
this.portalList.getListInformation().then(data => {
this.infolist = data;
});
並在提供者中:
return new Promise((resolve,reject) => {
this.http.get(url).subscribe(
data => {
const response: any = data;
resolve(response);
},
(error) => {
reject(error);
})
});
我的.spec.ts在這里。
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());
});
我為提供者提供了Mock。
export class PortalListMock {
public infoList = [{name: "MAC", region: "West"}];
public _getPortal(): any { return {} };
public getListInformation() { return this.infoList; }
return;
}
在執行**npm test**
,它會給出類似**this.portalList.getListInformation().then is not a function**
錯誤。
如何模擬提供程序http請求的承諾。 或如何克服這個問題。
我相信這與您返回數組而不是Promise有關。
我建議在模擬提供程序中進行以下更改:
這個:
public getListInformation() { return this.infoList; }
成為這個:
public getListInformation() { return Promise.resolve(this.infoList); }
這樣,您就返回了已解決的promise,它與真實提供程序中的代碼等效:
return new Promise((resolve,reject) => {
但僅限於返回始終包含靜態數據的已解決Promise。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.