在警报中单击“确定”或通过 jquery/javascript 确认对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7705817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:01:27  来源:igfitidea点击:

Clicking 'OK' on alert or confirm dialog through jquery/javascript?

javascriptjquerytestingclickautomated-tests

提问by PhD

I was thinking of writing some UI tests in backbone.js and jquery. They may not be the best way to do it but it's something that I was thinking about - to automate the tests without record and playback - through plain code.

我想在backbone.js 和jquery 中编写一些UI 测试。它们可能不是最好的方法,但这是我正在考虑的事情 - 通过纯代码使测试自动化,无需记录和回放。

The only thing that made me scratch my head using this approach is this: In some 'use-case flow' (of the execution) confirm/alert dialogs would show up. I'd like to click 'Ok' and continue the flow - is this even doable through plain javascript code? How?

使用这种方法唯一让我摸不着头脑的是:在某些“用例流程”(执行的)中,会出现确认/警报对话框。我想单击“确定”并继续流程 - 这甚至可以通过普通的 javascript 代码实现吗?如何?

Note: I do know GUI testing libraries exist, but I want to know how to do it using just jQuery/javascript code, if at all possible.

注意:我确实知道存在 GUI 测试库,但我想知道如何仅使用 jQuery/javascript 代码(如果可能的话)。

回答by Alnitak

As far as I know if you use a standard alert()call you cannot trigger an "OK" click because the alert call blocks the normal JS event loop.

据我所知,如果您使用标准alert()调用,则无法触发“确定”单击,因为警报调用会阻止正常的 JS 事件循环。

However you shouldbe able to replace window.alertand window.confirmwith your own function that does nothing:

但是,您应该能够用自己的函数替换window.alertwindow.confirm什么都不做:

window.alert = function() {
    console.log.apply(console, arguments);
};

Place these at the top of your JS before anything else is loaded and any subsequent calls to alert()or confirm()will call these instead.

在加载任何其他内容之前将它们放在 JS 的顶部,并且任何后续调用alert()confirm()将调用它们。

回答by John Kurlak

You want something like:

你想要这样的东西:

<script type="text/javascript">
var oldConfirm = confirm;
var oldAlert = alert;

confirm = function() {
    return true;
};
alert = function() {
    return true;
}

var response = confirm("Is this OK?");

if (response) {
    alert("Yay");
}
else {
    alert("Boo");
}

confirm = oldConfirm;
alert = oldAlert;
</script>