CasperJs, how to repeat a step X times onWaitTimeout?

♀尐吖头ヾ 提交于 2019-12-01 01:51:42

I think can do this without a for loop, by clustering your code into parts and do this recursively:

var verifyFailedTest = function(number, repeatStep, trueReturn){
    var index = 0;
    function intermediate(){
        casper.then(function(){
            repeatStep();
            casper.waitFor(function checkReturnTrue(){
                    return trueReturn();
                }
                , function then() {
                    this.test.pass("Test passes after " + (index+1) + " try");
                }
                , function timeout() { 
                    casper.reload();
                    if (index < number-1) {
                        intermediate();
                    } else {
                        lastTry();
                    }
                    index++;
                });
        });
    }
    function lastTry(){
        casper.then(function(){
            repeatStep();
            casper.waitFor(function checkReturnTrue(){
                    return trueReturn();
                }
                , function then() {
                    this.test.pass("Test passes after " + (index+1) + " try");
                });
        });
    }
    intermediate();
};

You'll have an error only after the number'th try.

But if you want to use your IIFE, the following might work by redefining thenFunction and skipping then block after you know that it is unnecessary (doBreak === true):

var verifyFailedTest = function(number, trueReturn, thenFunction){
    var i = 0, doBreak = false;
    var oldThenFunction = thenFunction;
    thenFunction = function(){
        doBreak = true;
        oldThenFunction();
    };
    for (; i <= number; i++){
        if (doBreak) {
            break;
        }
        // your IIFE here
        (function(index){
            if (index < number-1){
                //Execute 'number-1' times the then() step (reload the page each time) if timeout or until trueReturn returns true
                casper.then(function(){
                    if (doBreak) { return; }
                    casper.waitFor(...);
                });
            }
            //last execution, will return the normal error if it fails each time
            else if (index === number){
                casper.then(function(){
                    if (doBreak) { return; }
                    casper.waitFor(...);
                });
            }
            else{console.log('verifyFailedTest() bug');}
        })(i);
    }
};

Use CasperJS's repeat(int times, Function then) function.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!