Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Last active January 16, 2024 02:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DesignByOnyx/8384f190ba363d5003f73578c7e36285 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/8384f190ba363d5003f73578c7e36285 to your computer and use it in GitHub Desktop.
Helper for testing different environment variables for individual tests

This helper function allows you to define environment variables for individual tests. This works by setting the environment variables you define and then reloading the module defined by modulePath. In order to test the newly reloaded module, you cannot use top-level import, but rather the object returned by the loader function (see example).

IMPORTANT: You can only reload the module ONCE per test.

This helper takes care of resetting all environment variables before each test and after all tests. This should be invoked near the top of a describe block.

Example:

describe("Some Module", () => {
    const reloadModuleWithConfig = bootstrapEnvVarsTests<typeof import('./some-module')>('./some-module');

    it('throws if PORT is undefined', () => {
        // This must be used in leu of top-level import!
        const { someExport } = reloadModuleWithConfig({ PORT: undefined });
        expect(() => someExport()).toThrow();
    });

    it('works when FOOBAR is defined', () => {
        // Default exports must be aliased like this
        const { default: theMainModule } = reloadModuleWithConfig({ FOOBAR: 'foobar' });
        expect(theMainModule.isFoobar).toBe(true);
    });
});
const bootstrapEnvVarsTests = <ModuleType>(modulePath: string) => {
const OLD_ENV = process.env;
beforeEach(() => {
// this allows us to reassign env vars for individual tests
jest.resetModules();
process.env = { ...OLD_ENV };
});
afterAll(() => {
process.env = OLD_ENV;
});
return function reloadModule(envVars: Record<string, string>): ModuleType {
Object.assign(process.env, envVars);
// eslint-disable-next-line @typescript-eslint/no-var-requires
return require(modulePath);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment