Colingo / mock

Load a module with it's require's mocked out
MIT License
13 stars 3 forks source link

"Cannot find module" while require finds it without problem #3

Closed fatso83 closed 9 years ago

fatso83 commented 9 years ago

I cannot get this module to work at all.

        handler = require('../modules/requestHandler');
        handler = mock('../modules/requestHandler', /* line 14 */
            {
                '../modules/request_helpers/internalRequest': internalRequest 
            });
    });

just crashes Node with the error

Error: Cannot find module '../modules/requestHandler'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.require.resolve (module.js:384:19)
    at mock (/Users/fatso/dev/REST-API/node_modules/mock/index.js:15:29)
    at Context.<anonymous> (/Users/fatso/dev/REST-API/spec/requestHandler.test.js:14:19)

The require statement on line 13 works fine, so I am not sure what is going on there. I also turned on the debugging statement which shows this going on just before the crash:

RELATIVE: requested:../modules/requestHandler set ID to: /Users/fatso/dev/REST-API/node_modules/mock/modules/requestHandler from /Users/fatso/dev/REST-API/node_modules/mock/index.js
looking for "/Users/fatso/dev/REST-API/node_modules/mock/modules/requestHandler" in ["/Users/fatso/dev/REST-API/node_modules/mock"]

This seems to indicate that it does not look for the module from the project root, but only in its node_modules directory. Or that it seems to regard the mock module as the actual package.

jtremback commented 9 years ago

Using require.resolve() can help here

const mock = require('mock')
const test = require('tape')

const toUpload = mock(require.resolve('../stores/toUpload.js'), {
  'react-native': {
    AsyncStorage: {
      getItem () {
        console.log('getItem')
      },
      setItem () {
        console.log('setItem')
      }
    }
  }
})

const flux = mock(require.resolve('../flux.js'), {
  [require.resolve('../stores/toUpload.js')]: toUpload
})

I've found that I need to surround all relative module paths with require.resolve(). I wonder if this can somehow be avoided? Makes sense I guess.

fatso83 commented 9 years ago

Hmm.. might be. It's been 8 months, and I no longer work on this project anymore, so I won't be able to verify the solution. I'll close this, and hope that someone else will find your solution.