- Notifications
You must be signed in to change notification settings - Fork14
Simulates a global browser environment using jsdom
License
lukechilds/browser-env
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Simulates a global browser environment using
jsdom
.
This allows you to run browser modules in Node.js 6 or newer with minimal or no effort. Can also be used to test browser modules with any Node.js test framework. Please note, only the DOM is simulated, if you want to run a module that requires more advanced browser features (likelocalStorage
), you'll need to polyfill that seperately.
Usebrowser-env@2
to support older Node.js versions.
❗️Important note
This module adds properties from the
jsdom
window namespace to the Node.js global namespace. This is explicitlyrecommended against byjsdom
. There may be scenarios where this is ok for your use case but please read through the linked wiki page and make sure you understand the caveats. If you don't need the browser environment enabled globally,window
may be a better solution.
npm install --save browser-env
Or if you're just using for testing you'll probably want:
npm install --save-dev browser-env
// Initrequire('browser-env')();// Now you have access to a browser like environment in Node.js:typeofwindow;// 'object'typeofdocument;// 'object'vardiv=document.createElement('div');// HTMLDivElementdivinstanceofHTMLElement// true
By default everything in thejsdom
window namespace is tacked on to the Node.js global namespace (excluding existing Node.js properties e.gconsole
,setTimout
). If you want to trim this down you can pass an array of required properties:
// Initrequire('browser-env')(['window']);typeofwindow;// 'object'typeofdocument;// 'undefined'
You can also pass a config object straight through tojsdom
. This can be done with or without specifying required properties.
require('browser-env')(['window'],{userAgent:'My User Agent'});// orrequire('browser-env')({userAgent:'My User Agent'});
You can of course also assign to a function:
varbrowserEnv=require('browser-env');browserEnv();// orimportbrowserEnvfrom'browser-env';browserEnv();
browser-env
can also be preloaded at node startup as:
node -r browser-env/register test.js
window
- Exports a jsdom window object
MIT © Luke Childs
About
Simulates a global browser environment using jsdom