![](/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.