jsdom-context-require

Allows you to require files in a jsdom window context.

Usage no npm install needed!

<script type="module">
  import jsdomContextRequire from 'https://cdn.skypack.dev/jsdom-context-require';
</script>

README

jsdom-context-require
API Stability TypeScript Styled with prettier Build status Test Coverage NPM Version Downloads

Creates a new require function which runs all required modules in a new jsdom window context instead of global. Supports custom require extensions and resolvers. Also automatically resolves browser fields in package.json.

Ultimately this allows you to run tests with JSDOM without exposing your nodejs globals, or using a bundler.

Installation

npm install jsdom jsdom-context-require -D

Note: JSDOM is required as a peerDependency as of jsdom-context-require@4

Example

./index.js

import createBrowser from "jsdom-context-require";

const browser = createBrowser({
  dir: __dirname, // The path to resolve new requires from.
  html: "<div>Hello World</div>" // Initial jsdom html.
  extensions: ..., // Same as require.extensions but only used in the jsdom context.
  // All other options forwarded to jsdom.
});

const titleSetter = browser.require("./set-document-title");

titleSetter("Updated!");

assert.equal(browser.window.document.title, "Updated!");

./set-document-title.js

const $ = require("jquery"); // Any subsequent requires are evaluated in the jsdom window as well.

typeof global; // undefined

module.exports = (title) => {
  document.title = title;
}

Contributions

  • Use npm test to build and run tests.

Please feel free to create a PR!