Created
January 22, 2020 16:44
-
-
Save dwsmart/47f90566763e2db5fc890d0319bf6562 to your computer and use it in GitHub Desktop.
Code Coverage in Puppetter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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