What is jsdom?
As Node and io.js merge in the future, I expect the new versions of jsdom to support the one, unified platform.
The Test Runner
it and all the normal test setup hooks that you like. Most importantly, it features the Nyan cat test reporter:
Mocha lets you choose your own assertion library. I like should.js.
To install both:
By default, Mocha wants a
/test directory in your project root in which to put its configuration and potentially your spec files, depending on how you like to organize your projects:
Inside of the
/test dir, let’s
vim mocha.opts and give it a place to configure jsdom and our other libs:
1 2 3
We have yet to write the
test/utils/dom.js file. We will. This file includes options for mocha. Line by line, we’re saying that before mocha runs tests, we want to load our
dom.js config, the
should.js library, and specify our reporter as
I’ve tried to come up with several configurations that will make jsdom work well with my React projects. This is the best/simplest that I’ve come up with. I’d be interested to hear if you have any suggestions on the approach.
Here’s the full configuration with explanatory comments inline, as it would appear in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
The reason that we want to attach all the
window properties to the mocha
global object is because developers often write code that is meant for the browser without explicitly using the global environment object. For instance, in React the developers write:
window.navigator and putting it on
global.navigator, you’d get an error like this when running your tests:
The React Test
You are now ready to render React components into a document in your tests. The document will be provided by jsdom. You don’t need a browser environment to run this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
To run mocha with the configuration above, I like to add an npm script in
1 2 3 4 5
And then type:
Write the source to satisfy your test, and the lights should go green. Your DOM is happy. Your test is happy.
Does it work well for you? How might you improve on it? Enjoy testing!