revertable-globals

Sets globals that can be easily reverted to restore the original environment; useful for testing code that relies on the presence of certain globals.

Usage no npm install needed!

<script type="module">
  import revertableGlobals from 'https://cdn.skypack.dev/revertable-globals';
</script>

README

revertable-globals

npm version CI status

Sets globals in a JavaScript environment that can be easily reverted to restore the original environment; useful for testing code that relies on the presence of certain globals.

Installation

To install with npm, run:

npm install revertable-globals --save-dev

Exports

These ECMAScript modules are published to npm and exported via the package.json exports field:

revertableGlobals.mjs

Export default

Function revertableGlobals — Sets globals that can be easily reverted to restore the original environment.

Parameters
  1. globals: Record<string, unknown> — Map of globals to set.
  2. namespace ?: Record<string, unknown> — Namespace for the globals. Defaults to globalThis.
Returns

() => void — Function that reverts the globals.

Example 1

Ways to import.

import revertableGlobals from "revertable-globals";
import revertableGlobals from "revertable-globals/revertableGlobals.mjs";
Example 2

How to set and revert fetch related globals for a test.

import fetch, { Request, Response } from "node-fetch";
import revertableGlobals from "revertable-globals";

const revertGlobals = revertableGlobals({
  fetch,
  Request,
  Response,
});

try {
  // Test assertions here…
} finally {
  revertGlobals();
}
Example 3

How to set and revert an environment variable at runtime for a test.

import revertableGlobals from "revertable-globals";

const revertEnv = revertableGlobals({ FORCE_COLOR: "1" }, process.env);

try {
  // Test assertions here…
} finally {
  revertEnv();
}