如何在 Ionic 中创建 AlertController 模拟

迭戈·格里洛

我正在用 Jasmine 测试我的 Ionic 3 应用程序,我想知道如何模拟一个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模拟,例如,用户按下“是”按钮,以便我可以测试“是”按钮处理程序中的代码。按照我的单元测试。

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-mocks(下面的链接),但我不知道如何在警报中强制按钮动作。https://www.npmjs.com/package/ionic3-mocks

安德鲁·艾森伯格

我并不完全熟悉 ionic,但最终,这只是 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()
}

然后您可以直接在您的测试中测试这些处理程序。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章