简体   繁体   English

如何使用 Jest + Puppeteer 测试显示的警报?

[英]How to test an alert displaying using Jest + Puppeteer?

I need to verify that after a button click an alert is displayed.我需要验证单击按钮后是否显示警报。

I tried the following:我尝试了以下方法:

  it('should display an alert when the user tries to add empty value', () => {
    jest.setTimeout(100000);
    page.alert = jest.fn(text => text);
    const addButtonSelector = '#root > div > div > div.ToDoInput > button';
    expect(page).toClick(addButtonSelector);
    expect(page.alert).toHaveBeenCalledWith('Please enter a todo!');
  })

But the test Fails with zero calls to the page.alert (in reality the alert is shown after the click on this button in this conditions).但是测试失败,对 page.alert 的调用为零(实际上,在这种情况下单击此按钮后会显示警报)。 Also I tried window.alert - it is not recognized.我也试过 window.alert - 它无法识别。 Please help.请帮忙。

Update: I tried like that, and the alert function is not replaced with the mock function (???)更新:我试过这样,警报 function 不会被模拟 function 取代(???)

it('should display an alert when the user tries to add empty value', async() => {
    jest.setTimeout(50000);
    const dialogHandler = jest.fn();
    page.on('dialog', dialogHandler);
    const addButtonSelector = '#root > div > div > div.ToDoInput > button';
    await expect(page).toClick(addButtonSelector);
    await expect(dialogHandler).toHaveBeenCalled();
    const [firstCall] = dialogHandler.mock.calls;
    const [dialog] = firstCall;
    expect(dialog.message()).toEqual('Please enter a todo!');
  })

Take a look at Pupeteer's Dialog .看看Pupeteer 的 Dialog You can set event handler once a Dialog is displayed and if you pass jest.fn() you can have reference to the dialog that it has been called with您可以在显示 Dialog 后设置事件处理程序,如果您通过jest.fn()您可以引用已调用它的对话框

eg:例如:

describe('page with dialog', () => {
  const dialogHandler = jest.fn(dialog => dialog.dismiss());
  beforeAll(() => {
    page.on('dialog', dialogHandler);
  });

  describe('when the ToDoInput button is clicked', () => {
    beforeAll(async () => {
      await page.click('#root > div > div > div.ToDoInput > button');
    });

    it('should display a dialog', () => {
      expect(dialogHandler).toHaveBeenCalled();
    });

    it('should have message "Please enter a todo!"', () => {
      const [firstCall] = dialogHandler.mock.calls;
      const [dialog] = firstCall;
      expect(dialog.message()).toEqual('Please enter a todo!');
    });
  });
});

Edit: after testing it the only thing that was not working is that the test script was becoming idle until the dialog is either accepted or dismissed and after changing the dialogHandler to dismiss the dialog made it work flawlessly:编辑:在对其进行测试之后,唯一不起作用的是测试脚本变得空闲,直到对话框被接受或关闭,并且在更改dialogHandler以关闭对话框后,它可以完美地工作:

const dialogHandler = jest.fn(dialog => dialog.dismiss());

here is a working example这是一个工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM