dce-selenium
Version:
Selenium library to simplify testing and automatically snapshot the DOM.
64 lines (53 loc) • 1.95 kB
JavaScript
const fs = require('fs');
const getSnapshotFilenamePrefix = require('./getSnapshotFilenamePrefix');
module.exports = async (webdriver, suffix) => {
// Skip if no snapshots are being taken
if (global.dceSeleniumConfig.noSnapshots) {
return;
}
/*------------------------------------------------------------------------*/
/* Snapshot image */
/*------------------------------------------------------------------------*/
// Create a filename
const filenamePrefix = getSnapshotFilenamePrefix(suffix);
try {
const pageHasntLoaded = await webdriver.executeScript('return document.getElementsByTagName("body")[0].innerHTML.length === 0');
if (pageHasntLoaded) {
throw new Error();
}
} catch (err) {
fs.writeFileSync(`${filenamePrefix}.txt`, 'No page loaded yet');
return;
}
// Take the screenshot
try {
// Capture image
const image = await webdriver.takeScreenshot();
// Generate filename
const filename = `${filenamePrefix}-screenshot.png`;
// Write whole image to file
fs.writeFileSync(filename, image, 'base64');
} catch (err) {
// Could not create a screenshot
/* eslint-disable no-console */
console.log('\nCould not create a snapshot!');
console.log(err);
process.exit(0);
}
/*------------------------------------------------------------------------*/
/* Snapshot Source */
/*------------------------------------------------------------------------*/
try {
fs.writeFileSync(
`${filenamePrefix}-source.html`,
await webdriver.executeScript('return document.documentElement.outerHTML'),
'utf-8'
);
} catch (err) {
// Could not capture page source
/* eslint-disable no-console */
console.log('\nCould not capture page source!');
console.log(err);
process.exit(0);
}
};