doberkofler
doberkofler

Reputation: 10341

How to wait in webdriverjs for takeScreenshot to have the screenshot taken

I use the following type of code to take a screenshot:

var promise = driver.takeScreenshot();
promise.then(function (data) {
    var base64Data = data.replace(/^data:image\/png;base64,/, '');
    fs.writeFileSync('screenshot.png', base64Data, 'base64');
});

Because of the async nature of takeScreenshot, the screenshot unfortunately will be taken at an arbitrary point in time and if in the meantime the application throws an exception, no screenshot will be written at all.

What is the proper way to have screenshots taken synchronously using webdriverjs ?

Upvotes: 0

Views: 1005

Answers (1)

nilesh
nilesh

Reputation: 14279

I usually take screenshots in the After hooks. Below is sample code for the after Hook in cucumberjs. If you are using mocha, it has hooks as well.

 this.After(function (scenario, callback) {
        if(scenario.isFailed()){
            driver.takeScreenshot().then(function (buffer) {
                scenario.attach(new Buffer(buffer, 'base64').toString('binary'), 'image/png');
            });
        }
        driver.quit().then(function () {
                callback();
        });
 });

Here are some excerpts from WebDriverJS docs. So before taking screenshot, you can send a wait command to WebDriver for a certain condition and THEN take a screenshot too. In general test framework after hooks work the best

WebDriverJS uses a promise "manager" to coordinate the scheduling and execution of all commands.

The promise manager maintains a queue of scheduled tasks, executing each once the one before it in the queue is finished.

Upvotes: 2

Related Questions