Setting up JSDOM with Mocha

mythereal picture mythereal · May 14, 2017 · Viewed 8.2k times · Source

I'm trying to use sinon's mock and spy for testing Redux components and async actions, but as soon as I import sinon into any test file, running the following npm script:

mocha --require test/helpers/browser.js --compilers .:babel-core/register --opts test/client/**/*.{js,jsx} --recursive test/client

I get the following error:

var div = typeof document !== "undefined" && document.createElement("div");
                                                      ^

TypeError: document.createElement is not a function at .../node_modules/sinon/lib/sinon/util/core/deep-equal.js:3:55

browser.js is where I set up JSDOM:

import { JSDOM } from 'jsdom';

const doc = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');
cost win = doc.defaultView; // tried doc.window;

global.document = doc;
global.window = win;

/*
Object.keys(win).forEach(property => {
  if (typeof global[property] === 'undefined') {
    global[property] = win[property];
  }
});
*/

global.navigator = {
  userAgent: 'node.js'
};

I imagine I don't have jsdom set up correctly? I tried looking around and found the commented code in the browser.js file above, but it produces the error when uncommented:

Object.keys(win).forEach(function (property) {
       ^

TypeError: Cannot convert undefined or null to object.

Answer

ccprog picture ccprog · May 14, 2017

document is a property of window, not the other way round:

const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>');

global.window = dom.window;
global.document = dom.window.document;