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.
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);
});
});