Skip to content

Instantly share code, notes, and snippets.

@dwsmart

dwsmart/codeCover.js

Created Jan 22, 2020
Embed
What would you like to do?
Code Coverage in Puppetter
// npm install puppeteer
const puppeteer = require('puppeteer');
/* variables to allow for user-agent / screensize choice
example use: URL='https://tamethebots.com' useragent='Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)' viewportw=412 viewporth=732 node codeCover.js
*/
const url = process.env.URL || 'https://www.example.com';
const useragent = process.env.useragent || 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)';
const viewportw = process.env.viewportw || 1920;
const viewporth = process.env.viewporth || 1696;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setUserAgent(useragent);
await page.setViewport({
width: parseInt(viewportw),
height: parseInt(viewporth)
});
// start collecting coverage
await Promise.all([page.coverage.startJSCoverage(), page.coverage.startCSSCoverage()]);
try {
// load page and await until idle.
await page.goto(url, {
waitUntil: 'networkidle0'
});
// Stops collecting
const [coverageJScript, coverageCss] = await Promise.all([
page.coverage.stopJSCoverage(),
page.coverage.stopCSSCoverage()
]);
// Work out Used & Unused
const calcUsed = (type, coverage) =>
coverage.map(({
url,
ranges,
text
}) => {
let usedBytes = 0;
ranges.forEach(range => (usedBytes += range.end - range.start - 1));
if (parseInt(text.length - usedBytes) > 0) {
return {
url,
type,
usedBytes,
totalBytes: text.length,
unusedBytes: parseInt(text.length - usedBytes),
unusedPercent: parseFloat((parseFloat(text.length - usedBytes) / text.length * 100).toFixed(2))
};
} else {
return {
url,
type,
usedBytes,
totalBytes: text.length,
unusedBytes: parseInt(text.length - usedBytes),
unusedPercent: 0
};
}
});
let outputArray = [
...calcUsed('js', coverageJScript),
...calcUsed('css', coverageCss)
]
console.log(JSON.stringify(outputArray));
await browser.close();
} catch (err) {
console.log('Error loading page:', err);
await browser.close();
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment