Luke Childs
370dc71cf6
|
8 years ago | |
---|---|---|
src | 8 years ago | |
test | 8 years ago | |
.gitignore | 8 years ago | |
.travis.yml | 8 years ago | |
LICENSE | 8 years ago | |
README.md | 8 years ago | |
package.json | 8 years ago |
README.md
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.
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 = require('window');
const window = new Window();
const div = window.document.createElement('div');
// HTMLDivElement
div instanceof window.HTMLElement
// true
Because window
is just a normal JavaScript object it can be used more efficiently with object destructuring.
const { document } = new Window();
document.body.innerHTML = '<div class="foo">Hi!</div>';
document.body.querySelector('.foo').textContent;
// "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 = new Window(jsdomConfig);
window.navigator.userAgent;
// "Custom UA"
Universal Testing Pattern
You can use a really simple pattern to enable your browser modules to run in Node.js with window
. 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
.
module.exports = function(text, win) {
win = win || window;
win.document.body.innerHTML = `<h1>${text}</h1>`;
return window.document.querySelector('h1');
};
Browser usage:
module('Hi');
// <h1>Hi</h1>
Node.js usage:
module('Hi', new Window());
// <h1>Hi</h1>
License
MIT © Luke Childs