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

后端 未结 2 631
粉色の甜心
粉色の甜心 2021-02-07 13:05

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 wi

相关标签:
2条回答
  • 2021-02-07 13:38

    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>
    
    0 讨论(0)
  • 2021-02-07 13:42

    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.

    However you should be able to replace window.alert and window.confirm with your own function that does nothing:

    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.

    0 讨论(0)
提交回复
热议问题