38

I am using command:

mocha --compilers :./test/babel-setup.js --recursive --watch

It is giving error:

ReferenceError: window is not defined

I have the following in my babel-setup.js:

require("babel/register")({
  compact: false
});

I am using node 0.12.7 and "mocha": "^2.2.5" and "jsdom": "^3.1.2".

I already have jsdom installed with the project.

What is causing the error?

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
jit
  • 1,616
  • 3
  • 21
  • 49

3 Answers3

96

I was able to use jsdom-global to fix this issue. Follow the instructions in that link to install. Specifically, run

npm install --save-dev --save-exact jsdom jsdom-global

then add -r jsdom-global/register to your mocha command-line. When you re-run your tests, the window is not defined error will go away.

emmby
  • 99,783
  • 65
  • 191
  • 249
2

To test frontend libraries with mocha you need the node modul mocha-jsdom you find it here: https://www.npmjs.com/package/mocha-jsdom

Henry31
  • 105
  • 1
  • 11
0

Since I was doing too much with the window object, I just used this code to determine if I was in mocha or not.

function isMocha(){
    let context = (global || window);
    return ['afterEach','after','beforeEach','before','describe','it'].every(function(functionName){
        return context[functionName] instanceof Function;
    });
}
Adam Fowler
  • 1,750
  • 1
  • 17
  • 18