jsdom-context-require
v5.2.4
Published
Allows you to require files in a jsdom window context.
Downloads
745
Readme
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;
}
Additional browser apis
The result of createBrowser
api gives you a jsdom instance.
The following methods are added to the jsdom instance:
browser.require(id: string): Exports
This is the same as the require
function in node, except with all modules evaluated in the jsdom window's context.
browser.yield(): Promise
Waits for one macro task (setImmediate
) to occur in the browser.
browser.act(fn?: () => T): Promise<Awaited>
Runs and awaits a given (optional) function, then waits for a macro task (see browser.yield). This helper also keeps track of any uncaught errors within the browser context and will reject the promise with the error, or an AggregateError if there are any.
Contributions
- Use
npm test
to build and run tests.
Please feel free to create a PR!