项目作者: lukechilds

项目描述 :
Exports a jsdom window object.
高级语言: JavaScript
项目地址: git://github.com/lukechilds/window.git
创建时间: 2017-03-02T01:32:14Z
项目社区:https://github.com/lukechilds/window

开源协议:MIT License

下载


window

Exports a jsdom window object.

Build Status
Coverage Status
npm
npm

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

  1. npm install --save window

Or if you’re just using for testing you’ll probably want:

  1. npm install --save-dev window

Usage

  1. const Window = require('window');
  2. const window = new Window();
  3. const div = window.document.createElement('div');
  4. // HTMLDivElement
  5. div instanceof window.HTMLElement
  6. // true

Because window is just a normal JavaScript object it can be used more efficiently with object destructuring.

  1. const { document } = new Window();
  2. document.body.innerHTML = '<div class="foo">Hi!</div>';
  3. document.body.querySelector('.foo').textContent;
  4. // "Hi!"

Config

You can also pass a jsdom config object that will be passed along to the underlying jsdom instance.

  1. const jsdomConfig = { userAgent: 'Custom UA' };
  2. const window = new Window(jsdomConfig);
  3. window.navigator.userAgent;
  4. // "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.

  1. function createTitle(text, win) {
  2. win = win || (typeof window === 'undefined' ? undefined : window);
  3. const title = win.document.createElement('h1');
  4. title.innerHTML = text;
  5. return title;
  6. };
  7. module.exports = createTitle;

Browser usage:

  1. createTitle('Hi');
  2. // <h1>Hi</h1>

Node.js usage:

  1. const window = new Window();
  2. createTitle('Hi', window);
  3. // <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:

  1. function createTitle(text, opts = {}) {
  2. const doc = opts.document || window.document;
  3. const title = doc.createElement('h1');
  4. ...

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