admin管理员组

文章数量:1326317

I'm just starting with JS unit testing and while every tests are going well (I've went with Mocha) I'm having a problem while it requires some 'document's' attributes, like:

var baseTag  = document.getElementsByTagName('base');

it gives me the following error:

Mocha 'Uncaught ReferenceError: document is not defined'

my test run mand is:

mocha -u bdd test.js --reporter spec

now my question is, do I need some PhantomJS (or simillar tool) for testing when I need an acces for document's and DOM objects? Or I'm just opened for any advice how this should be resolved.

I'm just starting with JS unit testing and while every tests are going well (I've went with Mocha) I'm having a problem while it requires some 'document's' attributes, like:

var baseTag  = document.getElementsByTagName('base');

it gives me the following error:

Mocha 'Uncaught ReferenceError: document is not defined'

my test run mand is:

mocha -u bdd test.js --reporter spec

now my question is, do I need some PhantomJS (or simillar tool) for testing when I need an acces for document's and DOM objects? Or I'm just opened for any advice how this should be resolved.

Share Improve this question asked Dec 12, 2013 at 11:59 Oskar SzuraOskar Szura 2,5695 gold badges34 silver badges43 bronze badges 3
  • Have you tried window.document.getElementsByTagName()? – Bora Commented Dec 12, 2013 at 13:21
  • It won't help cause neither window neither document doesn't exist. As far for now I came up with the idea to 'mock-up' this object. – Oskar Szura Commented Dec 12, 2013 at 14:27
  • You can use something like mocha-phantomjs, but the easiest way in the long run is to use Karma to run your mocha tests. It will fire up the browsers and run your code inside those browser environments. You can also use it headless and just use PhantomJS. – oligofren Commented Dec 11, 2014 at 9:07
Add a ment  | 

1 Answer 1

Reset to default 5

Yes, you need to use something like PhantomJS or jsdom so to run your code against some sort of DOM tree. By default Node does not provide a DOM tree because it is rather specific functionality that most applications don't need.

What solution you want to select really depends on the code you are testing. I've had good results with jsdom to test code that only needs to navigate the nodes in a DOM tree. There is certainly a point at which jsdom won't do it. I'm not sure where the limit is.

本文标签: javascriptMocha 39Uncaught ReferenceError window is not defined39Stack Overflow