当Casperjs在另一个页面上时,它会加载任何URL

时间:2013-08-12 15:17:18

标签: phantomjs casperjs

我有两个网址X和Y.当casperjs在X页面上时,它必须调用Y页面,在得到响应之后它应该继续。

casper.start("X URL",function() {
   var casper2 = require('casper').create();

   casper2.start();
   casper2.open("Y URL", function() {
        RESPONSE
   });
   casper2.run();

}).then... >> It have to wait for response.

我该怎么办?

1 个答案:

答案 0 :(得分:8)

点击后您必须使用casper.then。这是一些代码:

var x = require('casper').selectXPath;
var url = 'http://stackoverflow.com/';

var casper = require('casper').create({
    verbose: false,
    logLevel: 'debug'
});

casper.test.comment('Starting Testing');

casper.start(url, function() {

    //console.log(this.getCurrentUrl());

    this.test.assert(
        this.getCurrentUrl() === url, 'url is the one expected'
    );

    this.test.assertHttpStatus(200, + 'site is up');

    casper.waitForSelector(x("//a[normalize-space(text())='Questions']"),
        function success() {
            this.test.assertExists(x("//a[normalize-space(text())='Questions']"));
            this.click(x("//a[normalize-space(text())='Questions']"));
        },
        function fail() {
            this.test.assertExists(x("//a[normalize-space(text())='Questions']"));
        }
    );   

    casper.then(function() {

            //console.log(this.getCurrentUrl());
            this.test.assertUrlMatches("http://stackoverflow.com/questions",
                "clicked through to questions page");
    });

    casper.thenOpen('http://reddit.com', function() {
        this.test.assertUrlMatches("http://www.reddit.com/",
                "On Reddit");
    });


});

casper.run(function() {
    this.echo('finished');
    this.exit();
});

基本上它转到stackoverflow.com,等到加载Questions按钮,点击它并检查重定向的URL是否有效。

如果您想查看特定网址,可以取消注释//console.log(this.getCurrentUrl());

现在假设您要转到一个全新的页面,我们可以使用thenOpen api

我强烈建议您阅读此博客:http://blog.newrelic.com/2013/06/04/simpler-ui-testing-with-casperjs-2/