README
revertable-globals
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
globals
:Record<string, unknown>
— Map of globals to set.namespace
?
:Record<string, unknown>
— Namespace for the globals. Defaults toglobalThis
.
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();
}