Casper js没有使用相同的结果

时间:2014-05-13 10:42:56

标签: javascript casperjs

我为我们的应用程序开发了CasperJS脚本。有时它工作正常,但有时它不像我们期望的那样工作。

你能帮帮我吗?我在哪里可以改进我的脚本来实现它?

请找到下面的脚本。

casper.test.comment('Tests for Add and Remove products');
var x= require('casper').selectXPath;
casper.start(navigationSupport.baseUrl);
casper.clear();
phantom.clearCookies();
casper.then(function() {
    // fill valid credentials
    var userName = 'asdf';
    var password = 'qwerty';
    this.fill('form#loginForm', {j_username: userName, j_password: password}, true);
    this.echo('Login successfully ');
    this.echo('Loged in user ::  '+userName);
});


casper.then(function(){
    this.capture('images/addRemove/step1_login.png', {
        top: 0,
        left: 0,
        width: 0,
        height: 0
    });
});


casper.then(function(){
    this.echo('Cart count before adding product:'+this.getHTML('div.cart-count.button_border')); 
    this.click(x('//div[@id="slider-body"]/table[@class="slider-item active"]/tbody/tr[1]/td[3]/div[@id="add-to-cart-standard2"]/input'));
    this.echo("1st Product added to the Cart:");
});


    casper.then(function(){
    this.wait(3000,function(){
    this.echo("Waiting");
    });
    });


casper.then(function(){
    this.capture('images/addRemove/step2_addtocart1.png', {
        top: 0,
        left: 0,
        width: 0,
        height: 0
    });
});


casper.then(function(){
    this.echo('Cart count after adding 1st product:'+this.getHTML('div.cart-count.button_border')); 
    this.click(x('//div[@id="slider-body"]/table[@class="slider-item active"]/tbody/tr[2]/td[3]/div[@id="add-to-cart-standard2"]/input'));
    this.echo("2nd Product added to the Cart:");
});


    casper.then(function(){
        this.wait(3000,function(){
            this.echo('Waiting..............');
        });
    });


casper.then(function(){
    this.capture('images/addRemove/step3_addtocart2.png', {
        top: 0,
        left: 0,
        width: 0,
        height: 0
    });
});

casper.then(function(){
    this.echo('Cart count after adding 2nd product:'+this.getHTML('div.cart-count.button_border')); 
    this.click(x('//header[@id="masthead"]/section/div/div[2]/form/nav/div/a'));
});

1 个答案:

答案 0 :(得分:2)

如果您的应用程序进行了一些AJAX调用(或任何异步),那么在AJAX调用完成之前,Casper可能会对“then”块进行评估。

更强大的方法是使用“waitForSelector”而不是“then”(或任何waitFor ...方法,具体取决于您的情况),以确保仅在预期结果可观察时才评估您的下一个测试步骤。 例如,如果您的AJAX调用用于生成<span class="result-item">

的列表
casper.waitForSelector("#result-item", function(){
  this.capture('images/addRemove/step3_addtocart2.png', {
    top: 0,
    left: 0,
    width: 0,
    height: 0
});