From 1082eee7065c9734a58027ff447b8d3aa5d7d308 Mon Sep 17 00:00:00 2001 From: Trey Griffith Date: Mon, 26 Nov 2018 10:16:09 -0800 Subject: [PATCH 1/3] add test illustrating issues re-requiring when mock-require is in the node path --- .gitignore | 1 + package.json | 2 +- test/runner.js | 6 +++++- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 3c3629e..e5409ad 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ node_modules +test/node-path/index.js diff --git a/package.json b/package.json index b79ed50..3e9ef2d 100644 --- a/package.json +++ b/package.json @@ -16,7 +16,7 @@ }, "scripts": { "lint": "eslint .", - "test": "NODE_PATH=test/node-path mocha ./test/runner" + "test": "cp index.js test/node-path/index.js && NODE_PATH=test/node-path mocha ./test/runner && rm test/node-path/index.js" }, "repository": { "type": "git", diff --git a/test/runner.js b/test/runner.js index 53fd1d1..caa4728 100644 --- a/test/runner.js +++ b/test/runner.js @@ -2,7 +2,7 @@ const assert = require('assert'); const normalize = require('normalize-path'); -const mock = require('..'); +const mock = require('./node-path/index'); describe('Mock Require', () => { afterEach(() => { @@ -78,6 +78,10 @@ describe('Mock Require', () => { assert.equal(mock.reRequire('.'), 'root'); }); + it('should support re-requiring names with collisions', () => { + assert.equal(mock.reRequire('./index'), 'root') + }) + it('should cascade mocks', () => { mock('path', { mocked: true }); mock('fs', 'path'); From 3f237d29a7e284073997d7c684102e667e6a2db4 Mon Sep 17 00:00:00 2001 From: Trey Griffith Date: Mon, 26 Nov 2018 10:20:26 -0800 Subject: [PATCH 2/3] when resolving paths using require.resolve, use the caller file as the location to resolve from, rather than the mock-require module itself --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index cc514a8..feb5e82 100644 --- a/index.js +++ b/index.js @@ -72,7 +72,7 @@ function isInNodePath(resolvedPath) { function getFullPath(path, calledFrom) { let resolvedPath; try { - resolvedPath = require.resolve(path); + resolvedPath = require.resolve(path, { paths: [ calledFrom ]}); } catch (e) { // do nothing } From baeda0af58475f270e66f0071f5a4161727f2e0c Mon Sep 17 00:00:00 2001 From: Trey Griffith Date: Tue, 27 Nov 2018 20:51:52 -0800 Subject: [PATCH 3/3] make require resolution backward compatible --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index feb5e82..bebad76 100644 --- a/index.js +++ b/index.js @@ -72,7 +72,7 @@ function isInNodePath(resolvedPath) { function getFullPath(path, calledFrom) { let resolvedPath; try { - resolvedPath = require.resolve(path, { paths: [ calledFrom ]}); + resolvedPath = Module._resolveFilename(path, Module._cache[calledFrom]); } catch (e) { // do nothing }