Skip to content

Instantly share code, notes, and snippets.

@maimArt
Last active January 21, 2019 06:14
Show Gist options
  • Save maimArt/9dfaf1844dba43514b6ef1757e6549c4 to your computer and use it in GitHub Desktop.
Save maimArt/9dfaf1844dba43514b6ef1757e6549c4 to your computer and use it in GitHub Desktop.
Screenshoter for protractor
const { writeFile, mkdirSync, existsSync } = require('fs');
/**
* Handles taking and saving screenshots in browserstack environment.
*/
class Screenshoter {
/**
* @param capabilityName name of capability used for saving the screenshots (must be valid for file names)
*/
constructor(capabilityName) {
this.screenshots = [];
this.capabilityName = capabilityName;
}
/**
* Takes a screenshot of the current screen.
* @param name functional name of the screenshot used for saving it (must be valid for file names)
* @return {promise.Promise<string | never>}
*/
async takeScreenshot(name) {
// waiting 5 seconds to be sure translation is done
return wait(5000).then(() =>
browser.driver.takeScreenshot().then(data => {
this.screenshots.push(new Screenshot(name, data));
})
);
}
/**
* Saves all taken screenshots to a local directory. (overrides already existing)
* Directory pattern: <target directory>/<screenshot name>/<screenshot name>__<capability name>.png
* @param targetDirectory root directory the screenshots should be saved (will be created if not exists)
*/
saveScreenshots(targetDirectory) {
createDirectoryIfNotExists(targetDirectory);
this.screenshots.forEach(screenshot => {
const subDir = targetDirectory + '/' + screenshot.name;
createDirectoryIfNotExists(subDir);
const screenshotFilename = subDir + '/' + screenshot.name + '__' + this.capabilityName + '.png';
writeFile(screenshotFilename, screenshot.data.replace(/^data:image\/png;base64,/, ''), 'base64', function(err) {
if (err) throw err;
});
console.log('Saved screenshot ' + screenshotFilename);
});
}
}
createDirectoryIfNotExists = function(directory) {
if (!existsSync(directory)) {
mkdirSync(directory);
}
};
wait = function(delayInMS) {
return new Promise(resolve => setTimeout(resolve, delayInMS));
};
class Screenshot {
constructor(name, data) {
this.name = name;
// raw image data
this.data = data;
}
toString() {
return name + ': ' + this.data;
}
}
module.exports.Screenshoter = Screenshoter;
module.exports.Screenshot = Screenshot;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment