- Notifications
You must be signed in to change notification settings - Fork9
Exports a jsdom window object.
License
lukechilds/window
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
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, usewindow@3
to support older Node.js versions.
npm install --save window
Or if you're just using for testing you'll probably want:
npm install --save-dev window
constWindow=require('window');constwindow=newWindow();constdiv=window.document.createElement('div');// HTMLDivElementdivinstanceofwindow.HTMLElement// true
Becausewindow
is just a normal JavaScript object it can be used more efficiently with object destructuring.
const{ document}=newWindow();document.body.innerHTML='<div>Hi!</div>';document.body.querySelector('.foo').textContent;// "Hi!"
You can also pass a jsdom config object that will be passed along to the underlying jsdom instance.
constjsdomConfig={userAgent:'Custom UA'};constwindow=newWindow(jsdomConfig);window.navigator.userAgent;// "Custom UA"
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 withwin
. Setwin
to the passed in window object if it exists, otherwise fallback to globalwindow
.
functioncreateTitle(text,win){win=win||(typeofwindow==='undefined' ?undefined :window);consttitle=win.document.createElement('h1');title.innerHTML=text;returntitle;};module.exports=createTitle;
Browser usage:
createTitle('Hi');// <h1>Hi</h1>
Node.js usage:
constwindow=newWindow();createTitle('Hi',window);// <h1>Hi</h1>
Obviously you don't need to follow this exact pattern, maybe you already have an options object and you only needdocument
not the entire window object:
functioncreateTitle(text,opts={}){constdoc=opts.document||window.document;consttitle=doc.createElement('h1'); ...
You can see an example of this pattern inlukechilds/create-node
. Specificallysrc/create-node.js andtest/unit.js.
Sometimes you may have dependencies that you can't pass a window object to. In that scenario you can alternatively usebrowser-env
which will simulate a global browser environment.
MIT © Luke Childs
About
Exports a jsdom window object.