Unit testing 如何在Ionic中创建AlertController模拟
我正在用Jasmine测试我的Ionic 3应用程序,我想知道如何模拟创建确认警报的Unit testing 如何在Ionic中创建AlertController模拟,unit-testing,ionic-framework,jasmine,ionic3,Unit Testing,Ionic Framework,Jasmine,Ionic3,我正在用Jasmine测试我的Ionic 3应用程序,我想知道如何模拟创建确认警报的AlertController 创建确认警报的功能如下所示: pressedButton:string=""; myAlert() { let confirm = this.alerCtrl.create({ title: 'Title', message: 'Some message here', buttons: [ {
AlertController
创建确认警报的功能如下所示:
pressedButton:string="";
myAlert() {
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: () => {
this.pressedButton = 'No';
}
},
{
text: 'Yes',
handler: () => {
this.pressedButton = 'Yes';
}
}]
});
confirm.present()
}
基本上,我想要的是为AlertController
创建一个模拟,例如,模拟用户按下“yes”按钮,以便我可以在yes按钮处理程序中测试代码。在我的单元测试之后
beforeEach(() => {
fixture = TestBed.createComponent(MyPage);
comp = fixture.componentInstance;
});
it('should set pressedButton to "Yes" when the user press the "Yes" button', () => {
comp.myAlert(); //I want a mock that simulates the Yes button being pressed
expect(comp.pressedButton).toEqual('Yes');
});
我已经看过了ionic3模拟(下面的链接),但我不知道如何在警报中强制按钮操作。
我对爱奥尼亚并不完全熟悉,但最终,这一切都只是JavaScript和HTML。您需要做的是获取与要单击的按钮对应的DOM元素,然后调用click方法 以下是可能有效的方法 向所有警报控制器按钮添加ID,如下所示:
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: () => {
this.pressedButton = 'No';
},
id: 'no-alert'
},
{
text: 'Yes',
handler: () => {
this.pressedButton = 'Yes';
},
id: 'yes-alert'
}]
});
confirm.present()
然后在测试中,抓住按钮元素:
let yesButton = document.getElementById('yes-alert');
yesButton.click();
...continue the test...
更新最好测试控制器本身,并确保所有操作都正确连接,但如果不可能,您可以直接测试处理程序代码 类似这样的方法会奏效:
export const yesHandler = () => ...
export const noHandler = () => ...
pressedButton:string="";
myAlert() {
let confirm = this.alerCtrl.create({
title: 'Title',
message: 'Some message here',
buttons: [
{
text: 'No',
handler: noHandler
},
{
text: 'Yes',
handler: yesHandler
}]
});
confirm.present()
}
然后,您可以在测试中直接测试这些处理程序。我正在使用Ionic 4(以前是3),添加新的模拟对我来说似乎也很麻烦。使用
AlertController
,您可以在我之前的评论中找到一些有用的东西:。如果我可以使用原始的AlertController,您的建议就行了。然而,当我尝试使用原始控制器时,我得到了这个问题中所述的错误:[这就是为什么我需要创建mock如果您不是测试实际控制器,而是测试控制器内部的代码,为什么不直接调用该代码?我将更新我的答案。无法在按钮对象中添加id这不是答案,更像是注释。