Skip to content

Instantly share code, notes, and snippets.

@KubaJastrz
Last active October 22, 2021 13:14
Show Gist options
  • Save KubaJastrz/7964fc0f7abb0a9c9b25b20b89e4bea3 to your computer and use it in GitHub Desktop.
Save KubaJastrz/7964fc0f7abb0a9c9b25b20b89e4bea3 to your computer and use it in GitHub Desktop.
Testing modules that use env variables in `jest`
const isDevelopment = process.env.NODE_ENV !== 'production'
export function log(...args) {
if (isDevelopment) {
console.log(...args)
}
}
export type Example = 'hello'
// You can import types safely, as they get stripped out in the parsed code
import { Example } from './01-example';
let OLD_ENV: string | undefined;
beforeAll(() => {
// Store the actual value so it can be restored after all test cases finish
OLD_ENV = process.env.NODE_ENV;
// You can also set a default value here for all tests, if you want:
// process.env.NODE_ENV = 'default'
// NOTE: in newer versions of `@types/node`, process.env is a Readonly object so TypeScript will complain
// You may need to add `@ts-ignore` above the assignment in such cases.
});
beforeEach(() => {
// Clear jest cache
jest.resetModules();
});
afterAll(() => {
process.env.NODE_ENV = OLD_ENV;
});
it('logs stuff in development', async () => {
// set value for this test case
process.env.NODE_ENV = 'development';
// import the module
const { log } = await import('./01-example');
// good old require would work too, but we want to preserve type safety!
// const { log } = require('./example')
const spy = jest.spyOn(console, 'log');
log('hello');
expect(spy).toHaveBeenCalledWith('hello');
});
it('does not log stuff in production', async () => {
process.env.NODE_ENV = 'production';
const { log } = await import('./01-example');
const spy = jest.spyOn(console, 'log');
log('hello');
expect(spy).not.toHaveBeenCalled();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment