JS on DOM & Code Coverage

Code Covering a DOM Utility

const $ = (css, p) => (p || document).querySelector(css);
const $$ = (css, p) => (p || document).querySelectorAll(css);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="lib/index.js"></script>
</head>
<body>
<p>first</p>
<p>second</p>
</body>
</html>
"scripts": {
"instrument": "istanbul instrument ./lib -o ./test/lib",
"test": "..."
}
const Nightmare = require('nightmare');
const nightmare = Nightmare({show: true});
nightmare
.goto(`http://localhost:8080/`)
// basic assert utility (console.assert is not intercepted)
.evaluate(() => {
window.assert = (ok, message) =>
console.warn('nightmare', !!ok, message || 'unknown');
})
// provide a mechanism to intercept asserts
.on('console', (type, ...args) => {
if (type === 'warn' && args[0] === 'nightmare') {
type = 'assert';
args.shift();
}
switch (type) {
case 'assert':
const [ok, message] = args;
if (!ok) exit(new Error(message));
else console.log(` \x1B[0;32m✔\x1B[0;0m ${message}`);
break;
case 'error':
exit(new Error(args[0]));
default:
console[type](...args);
}
})
// ... previous code ... 
// return at the end the coverage result
.evaluate(() => window.__coverage__)
.end()
.then(coverage => {
require('fs').writeFile(
require('path').join(__dirname, 'coverage.json'),
JSON.stringify(coverage),
(err) => {
if (err) exit(err);
}
);
})
.catch(exit)
function exit(error) {
console.error(error);
process.exit(1);
}
"test": "http-server -s test & node test && istanbul report --include=test/coverage.json text-summary"
console output until now

Start Covering With Tests

.on(...)
// execute tests
.evaluate(() => {
assert(
$('p').textContent === 'first',
'$ returns the first node'
);
})
.evaluate(...)
====== Coverage summary ======
Statements : 75% ( 3/4 )
Branches : 50% ( 2/4 )
Functions : 100% ( 0/0 )
Lines : 100% ( 2/2 )
==============================
assert($$('p').length === 2, '$$ returns a list of nodes');

One more thing …

assert(!$('p', document.head), '$(css, parent) query the parent');

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store