dce-selenium
Version:
Selenium library to simplify testing and automatically snapshot the DOM.
188 lines (167 loc) • 5.5 kB
JavaScript
/* eslint-disable no-console */
const path = require('path');
const { spawn } = require('child_process');
const W = process.stdout.columns;
const surroundWithBuffer = require('./surroundWithBuffer');
const consoleLog = require('./consoleLog');
/**
* Function that runs tests multiple times, once for each browser selected
* @param {string[]} [browsers=see description] –
* the list of browsers to test on. If excluded, we check for npm flags: run
* this script via npm run using any combination of --chrome, --safari, and/or
* --firefox. If no npm flags, browsers is set to all browsers: Chrome,
* Firefox, and Safari (if on a mac)
* @param {string} [snapshotTitle=current timestamp] – the title of the folder
* to put the snapshot in (test/snapshots/snapshotTitle)
* @param {function} [before] – an asynchronous function to call before starting
* tests
* @param {function} [after] – an asynchronous function to call after ending
* tests
* @param {string} [subfolder] – the subfolder within test/selenium to look for
* tests (looks in test/selenium/subfolder)
*/
module.exports = async (config = {}) => {
let {
browsers,
snapshotTitle,
} = config;
const {
before,
after,
subfolder,
} = config;
/*------------------------------------------------------------------------*/
/* Create Snapshot Name */
/*------------------------------------------------------------------------*/
if (!snapshotTitle) {
// Get timestamp of current date
const startTime = new Date();
const replaceAll = (str, search, replacement) => {
return str.replace(new RegExp(search, 'g'), replacement);
};
snapshotTitle = `${startTime.toLocaleDateString()} ${replaceAll(startTime.toLocaleTimeString(), ':', '-')}`;
}
/*------------------------------------------------------------------------*/
/* Get list of browsers */
/*------------------------------------------------------------------------*/
if (!browsers) {
try {
browsers = (
process.argv
.filter((x) => {
return x.startsWith('--');
})
.filter((x) => {
return (
x === '--chrome'
|| x === '--safari'
|| x === '--safari-stp'
|| x === '--firefox'
|| x === '--headless-chrome'
);
})
.map((x) => {
return x.replace('--', '');
})
);
} catch (err) {
console.log(`\nAn error occurred while trying to read arguments: ${err.message}`);
process.exit(0);
}
// Overwrite browsers if running via npm and flags were included
if (process.env.npm_config_argv) {
const args = JSON.parse(process.env.npm_config_argv).original;
const npmFlagBrowsers = args
.filter((flag) => {
return flag.startsWith('--');
})
.map((flag) => {
return flag.substring(2);
})
.filter((flag) => {
return (['chrome', 'firefox', 'safari', 'safari-stp', 'headless-chrome'].indexOf(flag) >= 0);
});
if (npmFlagBrowsers.length > 0) {
browsers = npmFlagBrowsers;
}
}
// Default to all browsers
if (!browsers || browsers.length === 0) {
browsers = ['chrome', 'firefox'];
if (process.platform === 'darwin') {
// Add safari for mac users
browsers.push('safari');
}
}
}
/*------------------------------------------------------------------------*/
/* Run each browser sequentially */
/*------------------------------------------------------------------------*/
const runSpecificBrowser = async (browser) => {
if (before) {
await before();
}
const testsPath = (
subfolder
? path.join(
process.env.PWD,
'test',
'selenium',
subfolder,
'**',
'*.js'
)
: path.join(
process.env.PWD,
'test',
'selenium',
'**',
'*.js'
)
);
const success = await new Promise((resolve) => {
const inst = spawn(
'node_modules/.bin/mocha',
[
testsPath,
'--exit',
'--reporter spec',
`--${browser}`,
`--snapshot-title ${snapshotTitle}`,
],
{
stdio: [process.stdin, process.stdout, process.stderr],
}
);
inst.on('exit', (code) => {
resolve(code === 0);
});
});
if (after) {
await after();
}
return success;
};
const runAllBrowsers = async () => {
/* eslint-disable no-await-in-loop */
const results = {};
for (let i = 0; i < browsers.length; i++) {
// Print start message
consoleLog('\u2588'.repeat(W));
consoleLog(surroundWithBuffer(`Browser: ${browsers[i]}`, ''));
consoleLog('\u2588'.repeat(W));
const success = await runSpecificBrowser(browsers[i]);
results[browsers[i]] = success;
}
// Print results
console.log('\nResults:');
Object.keys(results).forEach((browser) => {
console.log(`- ${browser}: ${results[browser] ? 'all tests passed' : 'error(s) occurred'}`);
});
};
return runAllBrowsers();
};
// Run if main
if (require.main === module) {
module.exports();
}