单元测试-在Ionic Framework中遇到Alert Controller问题 [英] Unit testing - Getting issue with Alert Controller in Ionic Framework
问题描述
我正在尝试为一个已调用或未调用的方法编写一个测试用例.在该方法内部,我正在调用警报确认框.
I am trying to write a testcase for a method which has been called or not. Inside that method, I am calling an alert confirmation box.
我遇到类似
失败:this.alertCtrl.create不是函数
Failed: this.alertCtrl.create is not a function
Component.ts
Component.ts
submitTicket(comments) {
if (comments.length > 0) {
const prompt = this.alertCtrl.create({
title: "<span> Improve Solution </span>",
message: "<span>" + 'Are you sure you want <br>' + "</span>" +
"<span>" + 'to submit this improvement' + "</span>",
enableBackdropDismiss: false,
buttons: [
{
text: 'Cancel',
handler: data => {
// Some stuff
}
},
{
text: 'Improve Solution',
handler: data => {
//Some stuff
}
}
]
});
prompt.present();
} else {
this.errorMsg = true;
}
}
组件规格
import {AlertControllerMock } from 'ionic-mocks';
beforeEach(async(()=> {
TestBed.configureTestingModule({
declarations: [ImprovedsolutionsPage],
imports: [
IonicModule.forRoot(ImprovedsolutionsPage),
HttpClientTestingModule
],
providers: [
NavController,
AppService,
AlertController,
ImprovedsolutionsPage,
{provide: ViewController, useClass: ViewControllerMock},
{provide: LoadingController, useClass: LoadingControllerMock},
{provide: AlertController, useClass: AlertControllerMock},
]
}).compileComponents
}))
beforeEach(()=> {
fixture=TestBed.createComponent(ImprovedsolutionsPage)
component=fixture.componentInstance
fixture.detectChanges()
})
it('should be call submitTicket method', async(()= > {
spyOn(component, 'submitTicket').and.callThrough()
let comment='Needs to improve in detailing '
component.submitTicket(comment)
expect(component.submitTicket).toHaveBeenCalled()
}))
在这里,我正在使用ionic-mocks模块,并导入了AlertControllerMock,如上面的代码所示.我使用的是离子版本3.为了进行测试,我使用的是Karma和茉莉花
Here I am using ionic-mocks module and I imported AlertControllerMock as shown in the above code. And I am using ionic version 3. For testing I am using Karma and jasmine
有人可以帮我解决这个问题.
Could someone please help me out in this issue.
推荐答案
[已更新] 这是我的提示:我无法检查您的模拟程序的实现.但是,请确保您有一个单独的布尔值var来证明是否在其他地方调用了模拟函数(例如create
).
[Updated] Here is my tip: I am not able to check your mock's implementation. However, make sure you have a separate boolean var to testify if the mocked function, for example, create
, is called elsewhere.
create(opts?: AlertOptions): Promise<HTMLIonAlertElement> {
this.createAlertCalled = true;
this.opts = opts;
const self = this;
return Promise.resolve(<HTMLIonAlertElement>{
present: (): Promise<void> => {
self.presentCalled = true;
return Promise.resolve();
}
});
}
随后,对提到的变量用spyOn
进行spyOn
并期望断言是真实的.
Subsequently, do a spyOn
with AlertControllerMock
on the mentioned variable and expect the assertion to be truthy.
这篇关于单元测试-在Ionic Framework中遇到Alert Controller问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!