My question is about unit testing javascript code using Mocha. Ultimately this may be a question about dependency-injection or Inversion of Control, I have a poor grasp on these concepts.
I’m trying to write a test which simply creates an instance of header.js and tests that it is an object. However anytime I do so my test blows up when it loads Modernizr, with the following error message. It seems to occur because Modernizr is dependent on running inside the browser, but my unit tests need to run on the command line.
/lib/modernizr.js:8
“MozAppearance”in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNod
^
TypeError: Cannot read property ‘parentNode’ of undefined
at /Users/devadmin/devenv/djscript/djscript-vendor/lib/modernizr.js:8:6291
I have some requirejs modules which are in the following hierarchy:
lib
└── pj
├── module
│ └── header
│ └── header.js
├── util
│ └── header
│ └── Util.js
└── widget
└── header
├── Header.js
└── view
├── HeaderView.js
└── NavView.js
header.js instantiates Header.js, which in turn creates a HeaderView and a NavView. Only HeaderView requires Modernizr.
Any hints as to how I can get this code into a testable state? Would it help to see how I packaged Modernizr for use with requirejs?
well, I haven’t used Mocha specifically but you should be able to create a fake Modernizr instance in your tests / harness by doing something like…
…before you try to load up your module under test. With that fake instance defined, your module under test should use the fake instead of the actual modernizr lib.
You are basically hijacking AMD’s “Named Module” (link: http://requirejs.org/docs/api.html#modulename) functionality to substitute the real modernizr with your fake. In this way you can explicitly test any states you need.
Hope it helps!