在Casperjs中执行嵌套循环



我是Casperjs的新手,我想根据外部数据源进行日常测试。但是,我在循环方面遇到了一些问题。

这是我的代码:

var url = ['http://google.com/','http://www.as.com'];
casper.test.begin('PruebaLoop', function (test) {
casper.start('about:blank',function() {
}); 
casper.then(function() {
        casper.viewport(1024, 768);
        //casper.echo(casper.getTitle());
});
console.log('url.length: ' + url.length)
for (i = 0; i < url.length; i++) {
        casper.thenOpen(url[i], function() { // open that link
        console.log('i: '+i);
        });
        casper.wait(5000, function() {
                this.echo("I've waited for a 5 seconds.");
        });
        casper.then(function() {
                    casper.capture('url'+i+'.png');
        }); 
}
casper.run(function() {
casper.echo('Test completado');
casper.test.done();
});
 });

从调试中,我总是得到2作为结果。我不知道为什么。你能帮我一下吗?

非常感谢!

我的解决方案是:

var urls = ['http://www.elpais.es','http://www.as.com'];
casper.test.begin('PruebaLoop', function (test) {

                    casper.start('auto:blank',function() {
                    console.log("-----------------------------------");
                    console.log("estoy en start ");
                }); 
                    casper.then(function() {
                        casper.viewport(1024, 768);
                        console.log("estoy en wiewport");
                        console.log("urls.length = " + urls.length);
                        console.log("-----------------------------------");
                });
          for(i = 0; i < urls.length; i++) {
            (function(index) {
              var url = urls[index]
                casper.thenOpen(url, function() {
                    console.log('index tiene el valor: '+ index);
                    console.log('i tiene el valor: '+ i);
                });
                casper.then(function() {
                    this.wait(5000);
                    console.log("estoy en wait: "+ index);
                });
                casper.then(function() {
                    this.wait(5000);
                    casper.capture("pagina"+index+".png");
                    console.log("estoy en capture: " + index);
                    console.log("-----------------------------------");
                }); 
              })(i);
        }
    casper.run(function() {
        casper.echo('Test completado');
        casper.test.done();
    });
 });

它是有效的。

最新更新