Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
protractor-cucumber auto screenshot failures
let {defineSupportCode} = require('cucumber');
defineSupportCode(({After}) => {
After(function(scenario, done) {
let world = this;
if (scenario.isFailed()) {
world.takeAndSaveScreenshot().then(function(filename) {
console.log(`Screenshot saved at ${filename}`); //eslint-disable-line no-console
done();
});
} else {
done();
}
});
});
let Q = require('q');
let fs = require('fs');
let path = require('path');
let {defineSupportCode} = require('cucumber');
defineSupportCode(({setWorldConstructor}) => {
setWorldConstructor(World);
});
function World() {
return {
takeAndSaveScreenshot
};
}
function takeAndSaveScreenshot() {
let timestamp = new Date().getTime();
return browser.waitForAngular()
.then(getHtml)
.then(saveHtml.bind(null, timestamp))
.then(browser.takeScreenshot.bind(browser))
.then(saveScreenshot.bind(null, timestamp));
}
function getHtml() {
return browser.executeScript('return arguments[0].outerHTML;', element(by.css('html')));
}
function screenshotsDir() {
let dir = path.resolve(__dirname, '..', '..', '..', 'build', 'screenshots');
mkdir(dir);
return dir;
}
function saveHtml(timestamp, html) {
let fileName = path.join(screenshotsDir(), `${timestamp}.html`);
return Q.nfcall(fs.writeFile, fileName, html);
}
function saveScreenshot(timestamp, stream) {
let fileName = path.join(screenshotsDir(), `${timestamp}.png`);
return Q.nfcall(fs.writeFile, fileName, new Buffer(stream, 'base64')).then(function() {
return fileName;
});
}
function mkdir(dir) {
try {
fs.mkdirSync(dir);
} catch (e) {
if (e.code !== 'EEXIST') {
throw e;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment