UNPKG

2.58 kBMarkdownView Raw
1# browser-env
2
3> Simulates a global browser environment using [`jsdom`](https://github.com/tmpvar/jsdom).
4
5[![Build Status](https://travis-ci.org/lukechilds/browser-env.svg?branch=master)](https://travis-ci.org/lukechilds/browser-env) [![Coverage Status](https://coveralls.io/repos/github/lukechilds/browser-env/badge.svg?branch=master)](https://coveralls.io/github/lukechilds/browser-env?branch=master) [![npm](https://img.shields.io/npm/dm/browser-env.svg)](https://www.npmjs.com/package/browser-env)
6
7Previously named `node-browser-environment`.
8
9This allows you to run browser modules in Node.js 4 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 (like `localStorage`), you'll need to polyfill that seperately.
10
11> ❗️**Important note**
12>
13> This module adds properties from the `jsdom` window namespace to the Node.js global namespace. This is explicitly [recommended against](https://github.com/tmpvar/jsdom/wiki/Don't-stuff-jsdom-globals-onto-the-Node-global) by `jsdom`. 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.
14
15## Install
16
17```shell
18npm install --save browser-env
19```
20
21Or if you're just using for testing you'll probably want:
22
23```shell
24npm install --save-dev browser-env
25```
26
27## Usage
28
29```js
30// Init
31require('browser-env')();
32
33// Now you have access to a browser like environment in Node.js:
34
35typeof window;
36// 'object'
37
38typeof document;
39// 'object'
40
41var div = document.createElement('div');
42// HTMLDivElement
43
44div instanceof HTMLElement
45// true
46```
47
48By default everything in the `jsdom` window namespace is tacked on to the Node.js global namespace (excluding existing Node.js properties e.g `console`, `setTimout`). If you want to trim this down you can pass an array of required properties:
49
50```js
51// Init
52require('browser-env')(['window']);
53
54typeof window;
55// 'object'
56
57typeof document;
58// 'undefined'
59```
60
61You can also pass a config object straight through to `jsdom`. This can be done with or without specifying required properties.
62
63```js
64require('browser-env')(['window'], { userAgent: 'My User Agent' });
65
66// or
67
68require('browser-env')({ userAgent: 'My User Agent' });
69```
70
71You can of course also assign to a function:
72
73```js
74var browserEnv = require('browser-env');
75browserEnv();
76
77// or
78
79import browserEnv from 'browser-env';
80browserEnv();
81```
82
83## License
84
85MIT © Luke Childs