是否可以在出现未处理的警报时自动关闭 JS 警报?

Possible to dismiss JS alerts automatically whenever an unhandled one appears?

我 运行 遇到的问题是,有时 JS 对话行为在被测试的应用程序中是不可预测的。我希望我可以说我可以为此做任何事情,但我不能,因为我只是在吃黄瓜时遇到这种奇怪的行为。此外,测试实际的对话框与我无关。换句话说,我们只想在它们发生时点击并关闭它们。

begin
    find('div', :text => 'Cancel').double_click # Click cancel
    accept_browser_dialog # We've got two dialogue boxes to click through
    accept_browser_dialog # That makes two.. but what if a third was created?
    # Wouldn't it be great if I could just dismiss them as they appeared?
rescue Selenium::WebDriver::Error::UnhandledAlertError # <- SOMETHING LIKE THIS
    accept_browser_dialog # Handled easy as pie.. in theory
end # etc etc etc

看我在上面标记的那一行。每次我点击 'Cancel' 时,都会有两个对话框需要点击,但有时 double_click 调用会弹出第三个对话框。除了玩计数对话之类的游戏,有什么方法可以简单地在出现未处理的警报错误时将其关闭?

如果您知道自己在做什么,并且 真的 必须不顾后果地绕过所有 JavaScript 警报和对话,您总是可以 follow this advice:

driver.execute_script("window.alert = function() {}")
driver.execute_script("window.prompt = function() {return null}")
driver.execute_script("window.confirm = function() {return true}")

这肯定比试图处理不可预测的多变行为更干净。

如果您指的是系统模式框(警告、确认、提示),当使用 selenium 驱动程序时,您可以尝试接受一个打开的警告,如果不存在则捕获引发的错误。

find('div', :text => 'Cancel').double_click # Click cancel
accept_browser_dialog # We've got two dialogue boxes to click through
accept_browser_dialog # That makes two.. but what if a third was created?
begin
  accept_alert(wait: 0.1)
rescue  Capybara::ModalNotFound
end