Skip to content

Commit

Permalink
Add NODE_PATH check and warning to tests runner
Browse files Browse the repository at this point in the history
  • Loading branch information
jhmaster2000 committed Mar 29, 2022
1 parent a183bb5 commit 20bc6ec
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions ava.config.cjs
Expand Up @@ -24,22 +24,40 @@ module.exports = {
* ts-node, from either node_modules or tests/node_modules.
*
* Another possibility of interference is NODE_PATH environment variable being set,
* and ts-node being installed in any of the paths listed in NODE_PATH, to fix this,
* and ts-node being installed in any of the paths listed on NODE_PATH, to fix this,
* the NODE_PATH variable must be removed from the environment *BEFORE* running ava.
* An error will be thrown when trying to run tests with NODE_PATH set to paths with ts-node installed.
*/

const { existsSync } = require('fs');
const { existsSync, realpathSync } = require('fs');
const rimraf = require('rimraf');
const { resolve } = require('path');
const { resolve, delimiter } = require('path');

remove(resolve(__dirname, 'node_modules/ts-node'));
remove(resolve(__dirname, 'tests/node_modules/ts-node'));

// Prove that we did it correctly
expect(() => {createRequire(resolve(__dirname, 'tests/foo.js')).resolve('ts-node')}).toThrow();
let resolved;
try {
expect(() => { resolved = createRequire(resolve(__dirname, 'tests/foo.js')).resolve('ts-node'); }).toThrow();
} catch (err) {
err.message = err.message.split('\n').slice(0, -1).join('\n') + `\nts-node unexpectedly resolved to external location: ${resolved}`;

// Check for NODE_PATH interference. See comment on line 26.
if (process.env.NODE_PATH) {
const NODE_PATH = process.env.NODE_PATH.split(delimiter).filter(f => f).map(f => realpathSync(resolve(__dirname, f)));
for (const path of NODE_PATH) {
if (resolved.includes(path)) {
err.message += `\n! WARNING: NODE_PATH is set and contains ts-node at ${path}`;
err.message += `\n! This can cause problems with tests. Please clear the NODE_PATH environment variable before running tests.\n`;
}
}
}

throw err;
}

function remove(p) {
if(existsSync(p)) rimraf.sync(p, {recursive: true})
if (existsSync(p)) rimraf.sync(p, {recursive: true});
}
}

0 comments on commit 20bc6ec

Please sign in to comment.