Running mocha test but Getting error: ReferenceError: document is not defined
Asked Answered
M

4

19

I am using mocha testing framework to test Http rest-api. I want to generate test-report for all test case, but when I ran mocha --reporter html > report.html
Getting following error

/usr/local/lib/node_modules/mocha/lib/reporters/html.js:263
  var div = document.createElement('div');
            ^
ReferenceError: document is not defined
    at fragment (/usr/local/lib/node_modules/mocha/lib/reporters/html.js:263:13)
    at new HTML (/usr/local/lib/node_modules/mocha/lib/reporters/html.js:53:14)
    at Mocha.run (/usr/local/lib/node_modules/mocha/lib/mocha.js:459:18)
    at Object.<anonymous> (/usr/local/lib/node_modules/mocha/bin/_mocha:393:18)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
Marked answered 26/9, 2015 at 7:22 Comment(0)
M
13

The reporter named html is only to be used when running Mocha in a browser. Running Mocha from the command line won't work with it.

There is a reporter named doc, which outputs "html documentation" according to mocha --reporters. By the way, when you run mocha --reporters you won't see html listed as a reporter, for the reason I've given above.

Meantime answered 26/9, 2015 at 13:4 Comment(0)
B
11

if you don't need to test it in a browser, then you can use jsdom-global:

mocha -r jsdom-global/register
Bhayani answered 17/12, 2018 at 15:58 Comment(1)
this somehow helped me a lot as otherwise, I don't have any mock for the DOM. Thank you!Demibastion
L
-1

You should use a headless browser to avoid this problem. Try with mocha-phantomjs.

Library answered 23/5, 2016 at 20:25 Comment(1)
This didn't work for me because I'm testing a Node.JS app and Mocha-PhantomJS expects browser-based tests.Glut
C
-1

I was able to solve a simpler version of this problem by conditionally defining document:

let document = (typeof document === "undefined") ? {} : document;

I expect you could use the same approach, but would need to set document to something that mocks createElement.

Cookshop answered 14/7, 2017 at 15:9 Comment(2)
That's not viable. The OP would have to mock not only createElement but getElementsByTagName, getElementById, devicePixeRatio, width, height, getContext, style, className, addEventListener, innerHTML, and many many more. That's a huge task. The HTML reporter expects a full-fledged DOM environment.Meantime
Oh, I missed that the error is in mocha's code, not the code being tested. That is a harder problem. The principle might still work, I think there are libraries that do mock a (near-)complete DOM, but I'm not sure that counts as "the same approach".Cookshop

© 2022 - 2024 — McMap. All rights reserved.