Skip to content

Instantly share code, notes, and snippets.

@szkrd
Created June 27, 2016 15:37
Show Gist options
  • Save szkrd/d4e922f868d02680f249910c9a39c305 to your computer and use it in GitHub Desktop.
Save szkrd/d4e922f868d02680f249910c9a39c305 to your computer and use it in GitHub Desktop.
babel + mocha + chai + sinon + jsdom + hacked require + browser window objects
/*eslint no-console: 0*/
// mocha unit tests setup, no e2e, probably no integ!
require('babel-core/register');
require('babel-polyfill');
const jsdom = require('jsdom');
const sinon = require('sinon');
const chai = require('chai');
const sinonChai = require('sinon-chai');
// use sinon with bdd
chai.use(sinonChai);
// horrible jsdom hacks
// mocha-jsdom is broken, these are here for the unit tests only
// for anything really dom related, we will need integration or e2e, with full webpack
const virtualConsole = jsdom.createVirtualConsole();
virtualConsole.on('jsdomError', (error) => console.error(error.stack, error.detail));
const document = jsdom.jsdom('<!doctype html><html><body></body></html>', { virtualConsole });
const window = document.defaultView;
global.document = document;
global.window = window;
// we should prefer jsdom or npm mock implementations over local fake constructs
global.location = { href: 'http://foo.bar.dev/' };
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
global.localStorage = require('localStorage');
global.sessionStorage = {};
for (let i in localStorage) { // clone with hasownprops
sessionStorage[i] = localStorage[i];
}
global.Modernizr = require('modernizr');
global.Modernizr.localstorage = true;
// "simulate" webpack magical loaders for node
var Module = require('module');
var originalRequire = Module.prototype.require;
Module.prototype.require = function(fileName){
let required = '';
try {
// scss, html, json and other exotic files would break node requires
// probably we can implement an existSync for fileName.js and fileName/index.js later
required = originalRequire.apply(this, arguments);
} catch (ex) {
if (ex.message.indexOf('Cannot find module') === -1) {
throw ex;
}
}
return required;
};
// mocha before, after
beforeEach(function beforeEac() {
this.sandbox = sinon.sandbox.create();
});
afterEach(function afterEach() {
this.sandbox.restore();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment