简体   繁体   English

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

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

I was thinking of writing some UI tests in backbone.js and jquery. 我在考虑在backbone.js和jquery中编写一些UI测试。 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. 它们可能不是最好的方法,但它是我正在考虑的事情 - 通过简单的代码自动化测试而无需记录和回放。

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? 我想点击“确定”并继续流程 - 这是否可以通过简单的JavaScript代码实现? How? 怎么样?

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代码,如果可能的话。

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()调用,则无法触发“OK”单击,因为警报调用会阻止正常的JS事件循环。

However you should be able to replace window.alert and window.confirm with 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()任何后续调用都会调用它们。

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>

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

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