From 36e81e511d48b39a282fe580aaa1d20c5f5d8dae Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Fri, 16 Jun 2017 12:40:10 +0200 Subject: [PATCH] Add testOnly util Fixes #32 --- README.md | 5 +++++ index.js | 12 +++++++++--- tests/test_basics.js | 21 ++++++++++++++++++++- 3 files changed, 34 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 365a5c9..f0b1130 100644 --- a/README.md +++ b/README.md @@ -169,6 +169,11 @@ const validatedConfig = envalid.cleanEnv( ) ``` +## Utils + +### testOnly + +A function called `testOnly` is exported. It returns its value if `NODE_ENV === 'test'`, otherwise it returns `undefined`. ## Motivation diff --git a/index.js b/index.js index 6aaa083..5b89ef2 100644 --- a/index.js +++ b/index.js @@ -3,6 +3,12 @@ const { EnvError, EnvMissingError, makeValidator, const extend = (x = {}, y = {}) => Object.assign({}, x, y) +function testOnly(testDefault) { + return process.env.NODE_ENV === 'test' + ? testDefault + : undefined +} + /** * Validate a single env var, given a spec object * @@ -41,8 +47,8 @@ function extendWithDotEnv(inputEnv, dotEnvPath = '.env') { // The react-native packager detects the require calls even if they // are not on the top level, so we need to hide them by concatinating // the module names. - const fs = require('f'+'s') - const dotenv = require('doten'+'v') + const fs = require('f' + 's') + const dotenv = require('doten' + 'v') let dotEnvBuffer = null try { @@ -121,5 +127,5 @@ function cleanEnv(inputEnv, specs = {}, options = {}) { } module.exports = { - cleanEnv, makeValidator, bool, num, str, json, url, email, EnvError, EnvMissingError + cleanEnv, makeValidator, bool, num, str, json, url, email, EnvError, EnvMissingError, testOnly } diff --git a/tests/test_basics.js b/tests/test_basics.js index 1aeff92..564c43a 100644 --- a/tests/test_basics.js +++ b/tests/test_basics.js @@ -1,5 +1,5 @@ const { createGroup, assert } = require('painless') -const { cleanEnv, EnvError, EnvMissingError, str, num } = require('..') +const { cleanEnv, EnvError, EnvMissingError, str, num, testOnly } = require('..') const { assertPassthrough } = require('./utils') const test = createGroup() const makeSilent = { reporter: null } @@ -146,3 +146,22 @@ test('NODE_ENV built-in support', () => { assert.strictEqual(cleanEnv({}, customSpec).isProduction, false) assert.strictEqual(cleanEnv({}, customSpec).isDev, false) }) + +test('testOnly', () => { + const processEnv = process.env.NODE_ENV + process.env.NODE_ENV = 'test' + let spec = { + FOO: str({ devDefault: testOnly('sup') }) + } + + process.env.NODE_ENV = processEnv + const env = cleanEnv({ NODE_ENV: 'test' }, spec) + assert.deepEqual(env, { NODE_ENV: 'test', FOO: 'sup' }) + + spec = { + FOO: str({ devDefault: testOnly('sup') }) + } + + assert.throws(() => cleanEnv({ NODE_ENV: 'production' }, spec, makeSilent), EnvMissingError) + assert.throws(() => cleanEnv({ NODE_ENV: 'development' }, spec, makeSilent), EnvMissingError) +})