Cucumber + 测试 JS 警报警报、测试、Cucumber、JS

2023-09-08 10:23:27 作者:命硬i

我正在尝试使用 Cucumber on Rails 测试 JS 确认对话框.我有一个 window.onbeforeunload 事件处理程序,如果您尝试离开该页面,它会提示您一个确认对话框,但我不知道如何测试它,有人知道如何做到这一点吗?

I'm trying to test a JS confirmation dialog with Cucumber on Rails. I have a window.onbeforeunload event handler that will prompt you with a confirmation dialog if you try to navigate away from the page but I have no idea how to test it, anyone have an idea on how this can be done?

推荐答案

您可以使用 selenium 的各种功能来捕获警报/确认.它们不能直接用于 webrat selenium 实现,但是当使用 webrat 的 config.mode = :selenium 时,它们可以按如下方式使用:

There are various functions of selenium you can use to capture alerts/confirms. They are not directly available with the webrat selenium implementation, but when using webrat's config.mode = :selenium they can be used as follows:

Then /^I should see a JS alert$/ do
    selenium.is_alert_present.should be_true
end

# or

Then /^I should see a "Are you sure?" JS confirm dialog$/ do
    selenium.get_alert.should eql("Are you sure?")
end

# you can also click the OK/Cancel buttons on confirm boxes with

selenium.chooseOkOnNextConfirmation();
#and
selenium.chooseCancelOnNextConfirmation();

可能没有最好的测试,但会给你一个想法.selenium 在内部覆盖了 JS 的 alert() 和 confirm() 函数,因此它可以捕获这些信息.

There are probably not the greatest tests, but gives you an idea. Internally selenium overrides the alert() and confirm() functions of JS so it can captures this information.

您可以在 selenium faq 或您的 gem 服务器上找到更多文档

You can find more docs on the selenium faq or on your gem server