【问题标题】:Continue test if a click error occurs继续测试是否出现点击错误
【发布时间】:2014-12-06 21:14:25
【问题描述】:

我正在使用 PhantomJS 运行 CasperJS。我让它转到一个 url 并单击一个基于 XPath 的元素。这可能会发生多次而没有问题,直到我怀疑页面加载存在延迟,它找不到 XPath,它会引发错误并停止测试。我希望它继续通过错误。我不想再等待+点击了,因为有很多点击正在进行,并且随机点击可能会出现错误,等待每次点击都会适得其反。

我已经尝试将整个测试放入 try catch,它不会捕获。

我能找到的唯一处理只是给出了有关错误的更多信息,仍然停止了测试。

【问题讨论】:

    标签: javascript xpath error-handling phantomjs casperjs


    【解决方案1】:

    我会等待您要运行的选择器,但超时时间很短。在成功功能中单击,在超时功能中报告问题(或什​​么都不做)。

    例如:

    casper.waitForSelector('a.some-class', function() {
        this.click('a.some-class');
        }, function onTimeout(){
        this.echo("No a.some-class found, skipping it.");
        },
        100);   //Only wait 0.1s, as we expect it to already be there
    });
    

    (如果您在此之前已经在执行casper.wait(),则将其替换为上述代码,并相应地增加超时时间。)

    【讨论】:

    • @Artjom,我不知道 - 我无法在 casper 文档中以一种或另一种方式看到任何明确的内容。我确信 1ms 的超时会起作用; 100 只是举例。
    【解决方案2】:

    您无法在异步执行的内容中捕获错误。所有then*wait* 函数都是异步的步进函数。

    Darren Cook 提供了good reliable solution。这里还有两个可能对你有用。

    casper.options.exitOnError

    CasperJS 为disable exiting on error 提供了一个选项。它工作可靠。 stacktrace 的完整错误会打印在控制台中,但脚本会继续执行。但是,当您还有其他可能要停止执行的错误时,这可能会产生不利影响。

    尝试捕捉

    在 CasperJS 中使用 try-catch 块有效,但仅适用于同步代码。以下代码显示了一个示例,其中仅打印错误消息而没有堆栈跟踪:

    casper.then(function() {
        try {
            this.click(selector);
        } catch(e){
            console.log("Caught", e);
        }
    });
    

    或更多集成:

    // at the beginning of the script
    casper.errorClick = function(selector) {
        try {
            this.click(selector);
        } catch(e){
            console.log("Caught", e);
            return false;
        }
        return true;
    };
    
    // in the test
    casper.then(function() {
        this.errorClick("someSelector");
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 2021-06-13
      • 2017-12-09
      • 1970-01-01
      相关资源
      最近更新 更多