From d48e0d767b424062b6ba54f3eed8d76cd2d96f1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=98yvind=20Saltvik?= Date: Tue, 14 Dec 2021 00:16:48 +0100 Subject: [PATCH] feat: added option to throw on missing env (#664) * feat: added option to throw on missing env * fix: passing tests for throwOnMissing --- README.md | 2 ++ index.js | 1 + node.js | 8 ++++++++ test/main.test.js | 19 +++++++++++++++++++ 4 files changed, 30 insertions(+) diff --git a/README.md b/README.md index be6ac30f..0d250d6e 100644 --- a/README.md +++ b/README.md @@ -556,6 +556,8 @@ Options: Default is `false`. * `dangerousExtend`: Disable security checks for `extend` query. Default is `false`. +* `throwOnMissing`: throw a error if env is not found. + Default is `false`. * `mobileToDesktop`: Use desktop browsers if Can I Use doesn’t have data about this mobile version. Can I Use has only data only about latest versions of mobile browsers. By default, `last 2 and_ff versions` diff --git a/index.js b/index.js index 73babdf1..8ef429df 100644 --- a/index.js +++ b/index.js @@ -397,6 +397,7 @@ var cache = {} * version in direct query. * @param {boolean} [opts.dangerousExtend] Disable security checks * for extend query. + * @param {boolean} [opts.throwOnMissing] Throw error on missing env. * @param {boolean} [opts.mobileToDesktop] Alias mobile browsers to the desktop * version when Can I Use doesn't have * data about the specified version. diff --git a/node.js b/node.js index 0e869d36..66e69d25 100644 --- a/node.js +++ b/node.js @@ -82,6 +82,14 @@ function pickEnv(config, opts) { name = 'production' } + if (opts.throwOnMissing) { + if (name && name !== 'defaults' && !config[name]) { + throw new BrowserslistError( + 'Missing config for Browserslist environment `' + name + '`.' + ) + } + } + return config[name] || config.defaults } diff --git a/test/main.test.js b/test/main.test.js index b313d634..d0c1ae2b 100644 --- a/test/main.test.js +++ b/test/main.test.js @@ -260,4 +260,23 @@ test('correctly works with not and one-version browsers', () => { equal(browserslist('last 1 Baidu version, not <2% in AT'), ['baidu 7.12']) }) +test('throws error on missing env', () => { + throws( + () => browserslist(null, { path: PACKAGE, throwOnMissing: true, env: 'test' }), + "Missing config for Browserslist environment 'test'." + ) +}) + +test('does not throw error on missing defaults env', () => { + equal( + browserslist(null, { path: PACKAGE, throwOnMissing: true, env: 'defaults' }), DEFAULTS + ) +}) + +test('does not throw error on missing env', () => { + equal( + browserslist(null, { path: PACKAGE, throwOnMissing: false, env: 'test' }), DEFAULTS + ) +}) + test.run()