Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up JSDOM with Mocha

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.

like image 299
mythereal Avatar asked May 14 '17 05:05

mythereal


1 Answers

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;
like image 176
ccprog Avatar answered Oct 30 '22 12:10

ccprog