document or window will fail since those globals aren’t defined. If we can’t run the code, this puts us back to using the contrived model of “mental compilation”. That puts a lot more stress on the interviewer as a human compiler, and is a less than ideal environment for the candidate.
jsdom
jsdom is a library that provides a fake browser environment in node. We reached out to CoderPad and they were willing to add jsdom to their list of allowed npm packages.By using jsdom, candidates are able to write and run their code in CoderPad as if it was running in a browser. The fundamental thing we want from jsdom is@Eli_White that's a great suggestion. I'll have it go out in the next release.
— CoderPad (@CoderPad) September 16, 2016
document. We can get that with the following line:
global.document = jsdom.jsdom('<div class="foo">my content</div>');
Code language: JavaScript (javascript)
For more information about how to use jsdom, check out their api: https://github.com/tmpvar/jsdom
Mocha
A common complaint about Mocha is that it doesn’t run in a very “node” like way. Mocha uses a special test runner which injects globals like `describe` and `it` and then runs the tests. We can use some of Mocha’s internal apis to run tests in node, and thus CoderPad. Paste this into a CoderPad and give it a run.const Mocha = require('mocha');
const mocha = new Mocha();
mocha.suite.emit('pre-require', this, 'solution', mocha);
describe('tests', () => {
it('should run', () => {
});
});
mocha.run();
Code language: JavaScript (javascript)
A full example
Putting this all together, we can have a candidate write code that requires the dom and validate it with Mocha tests. Here is a full example:const jsdom = require('jsdom');
const Mocha = require('mocha');
const assert = require('assert');
const mocha = new Mocha();
function getContentByClassName(className) {
const elements = document.getElementsByClassName(className);
if (elements.length === 0) {
return '';
}
return elements[0].textContent;
}
const topLevel = this;
mocha.suite.emit('pre-require', topLevel, 'solution', mocha);
describe('#getContentByClassName', () => {
it('should return an empty string if given a non existent class', () => {
topLevel.document = jsdom.jsdom('<div class="foo">my content</div>');
assert(getContentByClassName('bar') === '');
});
it('should return the content of a class', () => {
topLevel.document = jsdom.jsdom('<div class="foo">my content</div>');
assert(getContentByClassName('foo') === 'my content');
});
});
mocha.run();
Code language: JavaScript (javascript)