Browse Source

Add detailed comments

pull/19/head
Luke Childs 8 years ago
parent
commit
2d0fbec36f
  1. 24
      src/index.js

24
src/index.js

@ -1,6 +1,9 @@
import jsdom from 'jsdom'; import jsdom from 'jsdom';
import clone from 'clone'; import clone from 'clone';
// Default jsdom config.
// These settings must override any custom settings to make sure we can iterate
// over the window object.
const defaultJsdomConfig = { const defaultJsdomConfig = {
features: { features: {
FetchExternalResources: false, FetchExternalResources: false,
@ -8,28 +11,45 @@ const defaultJsdomConfig = {
} }
}; };
// Function to return a window object.
// Accepts a jsdom config object that will be merged with the default options.
// Config object must be cloned before passing through otherwise jsdom will add
// lots of properties to the original reference.
const createWindow = userJsdomConfig => { const createWindow = userJsdomConfig => {
const jsdomConfig = Object.assign({}, userJsdomConfig, defaultJsdomConfig); const jsdomConfig = Object.assign({}, userJsdomConfig, defaultJsdomConfig);
return jsdom.jsdom('<html><body></body></html>', clone(jsdomConfig)).defaultView; return jsdom.jsdom('<html><body></body></html>', clone(jsdomConfig)).defaultView;
}; };
// IIFE executed on import to return an array of global node properties that
// conflict with global browser properties.
const protectedproperties = (() => Object const protectedproperties = (() => Object
.getOwnPropertyNames(createWindow()) .getOwnPropertyNames(createWindow())
.filter(prop => typeof global[prop] !== 'undefined') .filter(prop => typeof global[prop] !== 'undefined')
)(); )();
// Sets up global browser environment
module.exports = (...args) => { module.exports = (...args) => {
// Extract options from args
const properties = args.filter(arg => Array.isArray(arg))[0]; const properties = args.filter(arg => Array.isArray(arg))[0];
const userJsdomConfig = args.filter(arg => !Array.isArray(arg))[0]; const userJsdomConfig = args.filter(arg => !Array.isArray(arg))[0];
// Create window object
const window = createWindow(userJsdomConfig); const window = createWindow(userJsdomConfig);
Object // Get all global browser properties
.getOwnPropertyNames(window) Object.getOwnPropertyNames(window)
// Remove protected properties
.filter(prop => protectedproperties.indexOf(prop) === -1) .filter(prop => protectedproperties.indexOf(prop) === -1)
// If we're only applying specific required properties remove everything else
.filter(prop => !(properties && properties.indexOf(prop) === -1)) .filter(prop => !(properties && properties.indexOf(prop) === -1))
// Copy what's left to node's global scope
.forEach(prop => global[prop] = window[prop]); .forEach(prop => global[prop] = window[prop]);
// Return reference to original window object
return window; return window;
}; };

Loading…
Cancel
Save