Utilities
A set of useful utility functions.
rstest.stubEnv
Type: (name: string, value: string | undefined) => Rstest
Temporarily sets an environment variable in process.env to the specified value. Useful for testing code that depends on environment variables.
- If
value is undefined, the variable will be removed from process.env.
- You can call this multiple times to stub multiple variables.
- Use
rstest.unstubAllEnvs() to restore all environment variables changed by this method.
Example:
rstest.stubEnv('NODE_ENV', 'test');
expect(process.env.NODE_ENV).toBe('test');
rstest.stubEnv('MY_VAR', undefined);
expect(process.env.MY_VAR).toBeUndefined();
rstest.unstubAllEnvs
Type: () => Rstest
Restores all environment variables that were changed using rstest.stubEnv to their original values.
- Call this after your test to clean up any environment changes.
- Automatically called before each test if
unstubEnvs config is enabled.
Example:
rstest.stubEnv('NODE_ENV', 'test');
// ... run some code
rstest.unstubAllEnvs();
expect(process.env.NODE_ENV).not.toBe('test');
rstest.stubGlobal
Type: (name: string | number | symbol, value: unknown) => Rstest
Temporarily sets a global variable to the specified value. Useful for mocking global objects or functions.
- You can call this multiple times to stub multiple globals.
- Use
rstest.unstubAllGlobals() to restore all globals changed by this method.
Example:
rstest.stubGlobal('myGlobal', 123);
expect(globalThis.myGlobal).toBe(123);
rstest.stubGlobal(Symbol.for('foo'), 'bar');
expect(globalThis[Symbol.for('foo')]).toBe('bar');
rstest.unstubAllGlobals
Type: () => Rstest
Restores all global variables that were changed using rstest.stubGlobal to their original values.
- Call this after your test to clean up any global changes.
- Automatically called before each test if
unstubGlobals config is enabled.
Example:
rstest.stubGlobal('myGlobal', 123);
// ... run some code
rstest.unstubAllGlobals();
expect(globalThis.myGlobal).toBeUndefined();