Skip to content

Commit dd04056

Browse files
committed
Fix npm prefix test failing under nvm
The test did not clear pre-existing `npm_config_prefix` env vars (e.g. set by nvm) before asserting its own value. Fixes #25
1 parent dd40979 commit dd04056

2 files changed

Lines changed: 17 additions & 4 deletions

File tree

index.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@ const readRc = filePath => {
1212
} catch {}
1313
};
1414

15-
// TODO: Remove the `.reduce` call.
16-
// eslint-disable-next-line unicorn/no-array-reduce
17-
const getEnvNpmPrefix = () => Object.keys(process.env).reduce((prefix, name) => /^npm_config_prefix$/i.test(name) ? process.env[name] : prefix, undefined);
15+
const getEnvNpmPrefix = () => {
16+
const key = Object.keys(process.env).find(name => name.toLowerCase() === 'npm_config_prefix');
17+
return key ? process.env[key] : undefined;
18+
};
1819

1920
const getGlobalNpmrc = () => {
2021
if (isWindows && process.env.APPDATA) {

test.js

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ import path from 'node:path';
44
import test from 'ava';
55
import {execa} from 'execa';
66

7-
const importFresh = async moduleName => import(`${moduleName}?${Date.now()}`);
7+
let importCounter = 0;
8+
const importFresh = async moduleName => import(`${moduleName}?${++importCounter}`);
89

910
const {default: globalDirectory} = await importFresh('./index.js');
1011

@@ -62,9 +63,20 @@ test.serial('yarn with PREFIX', async t => {
6263
});
6364

6465
test.serial('reload package and get npm.prefix with env', async t => {
66+
const savedKeys = Object.keys(process.env).filter(name => name.toLowerCase() === 'npm_config_prefix');
67+
const savedValues = Object.fromEntries(savedKeys.map(key => [key, process.env[key]]));
68+
69+
for (const key of savedKeys) {
70+
delete process.env[key];
71+
}
72+
6573
// eslint-disable-next-line camelcase
6674
process.env.npm_config_PREFIX = '/usr/local/lib';
6775
const {default: globalDirectory} = await importFresh('./index.js');
6876
t.is(globalDirectory.npm.prefix, '/usr/local/lib');
6977
delete process.env.npm_config_PREFIX;
78+
79+
for (const [key, value] of Object.entries(savedValues)) {
80+
process.env[key] = value;
81+
}
7082
});

0 commit comments

Comments
 (0)