我需要验证单击按钮后是否显示警报。
我尝试了以下方法:
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!');
})
但是测试失败,对 page.alert 的调用为零(实际上,在这种情况下单击此按钮后会显示警报)。 我也尝试了 window.alert - 它无法被识别。 请帮忙。
更新:我这样尝试过,警报函数没有被模拟函数替换(???)
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!');
})
最佳答案
看看Pupeteer's Dialog 。一旦显示对话框并且传递jest.fn(),您就可以设置事件处理程序您可以引用已调用的对话框
例如:
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!');
});
});
});
<小时/>
编辑:测试后唯一不起作用的是测试脚本变得空闲,直到对话框被接受或关闭以及更改dialogHandler
之后关闭对话框使其完美运行:
const dialogHandler = jest.fn(dialog => dialog.dismiss());
关于javascript - 如何使用 Jest + Puppeteer 测试警报显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58887985/