Search code examples
javascriptperformance-testingcasperjstiming

How can I capture how long waitFor() waited in CasperJS?


I'm using casperJS to test one application. Thing is, I want to capture how long it actually took to receive the element I'm waiting for with waitForSelector().

If I set the log level to debug, it shows in the console how long it took for the element I was waiting for to appear:
enter image description here

I want to get that value and store it in a variable. Is this possible with CasperJS / PhantomJS? If it's not, what framework could I use instead?


Solution

  • The do-it-yourself approach would be to take the time yourself which should be sufficiently accurate:

    var start;
    casper.then(function(){
        start = new Date().getTime();
    });
    casper.waitFor(...);
    casper.then(function(){
        this.echo("waitFor() took " + (new Date().getTime() - start) + " ms");
    });
    

    Of course this is not very reusable. It would be easier just to register to the "log" event:

    casper.on("log", function(logEntry){
        if (logEntry.message.indexOf("waitFor() finished in ") === 0) {
            var time = parseInt(logEntry.message.match(/\d+/)[0]);
            // TODO: do something with the time
        }
    });
    

    Note that this is asynchronous, but you can still schedule steps (then* and wait* functions) from the event handler.

    If you're also interested in the timeout case, then you can register to the "waitFor.timeout" event.