angular - 模拟提供者类以返回响应并处理承诺 - 使用 Jasmine 进行单元测试和使用 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); }
这样您就返回了已解决的承诺,这相当于真实提供者中的代码:
return new Promise((resolve,reject) => {
但仅限于返回已解决的 Promise,始终包括静态数据。
推荐阅读
- c - Web 服务器未接收到所有请求
- android - How to upload array of image links to Firestore
- jquery - 在新窗口上加载 html 后调用函数
- c - C编程,我做错了什么?斯特托克
- node.js - 我有 TypeError [ERR_INVALID_CALLBACK]: Callback must be a function
- javascript - .env 文件无法传递字符串值
- java - 如何检查文本文件中的空格
- java - 如何在 Java 中捕捉声音?
- c# - Arquivo make file para entrar em pastas
- windows - 通过 CMD 恢复标准软件安装路径的注册表项