rewire icon indicating copy to clipboard operation
rewire copied to clipboard

rewire('./relative-path') when rewire from external npm module

Open danosaure opened this issue 9 years ago • 3 comments

Hi,

I am exporting rewire from a utility (test-helpers) library so that I do not need to include it in all my projects. Doing so, I am unable to use the relative path to import the file.

const testHelpers = require('node-test-helpers');
Persistance = testHelpers.rewire('./persistence');

Running the above will output the following:

  1) server/persistence "before each" hook for "should export a class":
     Error: Cannot find module './persistence'
    at internalRewire (node_modules/rewire/lib/rewire.js:23:25)
    at Object.rewire (node_modules/rewire/lib/index.js:11:12)
    at Context.beforeEach (server/persistence.spec.unit.js:11:25)

I then need to import with absolute path:

const path = require('path');
const testHelpers = require('node-test-helpers');
const Persistence = testHelpers.rewire(path.join(__dirname, 'persistence'));

which saves me the npm install rewire in my project, but is then more to type.

Is there any ways to fix this? or is that my only possible workaround? For the record, this also happens with proxyquire, so I assume it has something to do with node itself.

Thanks.

danosaure avatar Feb 18 '17 22:02 danosaure

I got the same problem so google brought me here. I solved it by using path:

const path = require('path');

var scrappeteer = rewire(path.join(process.cwd(), 'src', 'scrappeteer.js')); // instead of '../src/scrappeteer.js'

chfw avatar Sep 04 '17 22:09 chfw

@chfw I would really suggest you to NOT use process.cwd(). That is dependent of where you are launching your process and you could be in another folder and this would fail. Just a word of advice.

danosaure avatar Sep 05 '17 18:09 danosaure

Yep, you are right. Advice taken.

chfw avatar Sep 05 '17 19:09 chfw