README
jsdom-context-require
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!