Enable DOM in Node.js
Enables DOM in Node.js
jsdom-global will inject
document,
windowand other DOM API into your Node.js environment. Useful for running, in Node.js, tests that are made for browsers.
Requires jsdom.
npm install --save-dev --save-exact jsdom jsdom-global
jsdom-global now requires jsdom v10 or above. If you need jsdom v9 and below, use the previous version (
[email protected]).
Just invoke it to turn your Node.js environment into a DOM environment.
require('jsdom-global')()// you can now use the DOM document.body.innerHTML = 'hello'
You may also pass parameters to jsdomGlobal() like so:
require('jsdom-global')(html, options). Check the jsdom.jsdom() documentation for valid values for the
optionsparameter.
To clean up after itself, just invoke the function it returns.
var cleanup = require('jsdom-global')()// do things
cleanup()
In tape, run it before your other tests.
require('jsdom-global')()test('your tests', (t) => { /* and so on... */ })
Simple: Use Mocha's
--requireoption. Add this to the
test/mocha.optsfile (create it if it doesn't exist)
-r jsdom-global/register
Advanced: For finer control, you can instead add it via mocha's
beforeand
afterhooks.
before(function () { this.jsdom = require('jsdom-global')() })after(function () { this.jsdom() })
If you prefer to use
importrather than
require, you might want to use
jsdom-global/registerinstead. Place it on top of your other import calls.
import 'jsdom-global/register' import React from 'react' import jQuery from 'jquery' // ...
If you use Browserify on your tests (eg: smokestack, tape-run, budo, hihat, zuul, and so on), doing
require('jsdom-global')()is a noop. In practice, this means you can use jsdom-global even if your tests are powered by browserify, and your test will now work in both the browser and Node.
test.js):
require('jsdom-global')()// ...do your tests here
browserify test.js | smokestack # run in a browser node test.js # or the console browserify test.js --no-bundle-external # also works (but why bother?)
browserify test.js -t babelify | smokestack # run in a browser (with babel) babel-node test.js # or the console
jsdom-global © 2016+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors (list).
ricostacruz.com · GitHub @rstacruz · Twitter @rstacruz