最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Mocha 'Uncaught ReferenceError: window is not defined' - Stack Overflow

programmeradmin7浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论