window
Exports a
jsdom
window object.
Exports a jsdom window object. This is useful for enabling browser modules to run in Node.js or testing browser modules in any Node.js test framework.
Requires Node.js v6 or newer, use window@3
to support older Node.js versions.
Install
npm install --save window
Or if you're just using for testing you'll probably want:
npm install --save-dev window
Usage
const Window = ; const window = ; const div = windowdocument;// HTMLDivElement div instanceof windowHTMLElement// true
Because window
is just a normal JavaScript object it can be used more efficiently with object destructuring.
const document = ; documentbodyinnerHTML = '<div class="foo">Hi!</div>';documentbodytextContent;// "Hi!"
Config
You can also pass a jsdom config object that will be passed along to the underlying jsdom instance.
const jsdomConfig = userAgent: 'Custom UA' ;const window = jsdomConfig; windownavigatoruserAgent;// "Custom UA"
Universal Testing Pattern
You can use a really simple pattern to enable your browser modules to run in Node.js. Just allow a window object to be passed in to your module and prepend any references to browser globals with win
. Set win
to the passed in window object if it exists, otherwise fallback to global window
.
{ win = win || typeof window === 'undefined' ? undefined : window; const title = windocument; titleinnerHTML = text; return title;}; moduleexports = createTitle;
Browser usage:
;// <h1>Hi</h1>
Node.js usage:
const window = ; ;// <h1>Hi</h1>
Obviously you don't need to follow this exact pattern, maybe you already have an options object and you only need document
not the entire window object:
{ const doc = optsdocument || windowdocument; const title = doc; ...
You can see an example of this pattern in lukechilds/create-node
. Specifically src/create-node.js and test/unit.js.
What about dependencies?
Sometimes you may have dependencies that you can't pass a window object to. In that scenario you can alternatively use browser-env
which will simulate a global browser environment.
License
MIT © Luke Childs