如果发生单击错误,请继续测试

时间:2014-12-06 21:14:25

标签: javascript xpath error-handling phantomjs casperjs

我用PhantomJS运行CasperJS。我将它转到URL并单击基于XPath的元素。这可能会发生几次没有问题,直到我怀疑页面加载有延迟,它无法找到XPath,它会抛出错误并停止测试。我希望它继续通过错误。我不想等待+点击任何超过我已经存在的时间,因为有很多点击进行,并且错误可以是随机点击,等待每次点击都会产生效果。

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

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

2 个答案:

答案 0 :(得分: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(),那么用上面的代码替换它,并相应地增加超时。)

答案 1 :(得分:1)

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

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

casper.options.exitOnError

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

的try-catch

使用try-catch块在CasperJS中工作,但仅适用于同步代码。以下代码显示了一个示例,其中只打印了没有stacktrace的错误消息:

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");
});
相关问题