5.2.3 • Published 2 months ago

jsdom-context-require v5.2.3

Weekly downloads
4
License
MIT
Repository
github
Last release
2 months ago

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!

5.2.3

2 months ago

5.2.2

3 months ago

5.2.1

3 months ago

5.2.0

3 months ago

5.1.1

4 months ago

5.1.0

4 months ago

5.0.0

4 months ago

4.0.9

4 months ago

4.0.8

12 months ago

4.0.7

1 year ago

4.0.5

2 years ago

4.0.6

2 years ago

4.0.4

2 years ago

4.0.3

2 years ago

4.0.2

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

4.0.1

3 years ago

4.0.0

3 years ago

3.1.0

3 years ago

3.0.0

3 years ago

2.0.1

4 years ago

2.0.0

4 years ago

1.0.1

6 years ago

1.0.0

6 years ago