thlorenz / proxyquire

🔮 Proxies nodejs require in order to allow overriding dependencies during testing.
MIT License
2.75k stars 100 forks source link

possible es2015 issues #115

Closed scaljeri closed 8 years ago

scaljeri commented 8 years ago

I'm trying to setup a simple test with proxyquire, but whatever I do it doesn't work

Here is a repo to reproduce.

main.js:

import proxyquire from 'proxyquire';

let bar = proxyquire('./bar', { './foo': () => {
    return 1;
}} );
console.log(bar());

bar.js:

 import foo from './foo';

 function bar() {
     return foo();
}
export default bar;

foo.js:

function foo() {
    return Math.random();
}
export default foo;

And when I run this:

$> ./node_modules/.bin/babel-node main.js
/Usersdev/tmp/mock/main.js:13
console.log(bar());
            ^

TypeError: bar is not a function
    at Object.<anonymous> (main.js:7:13)
    at Module._compile (module.js:413:34)
    ...

Does this has anything todo with es2015 or is it just me ?

NullDivision commented 8 years ago

import foo from './foo' equates to {default: function foo}.

To stub it you need to do:

let bar = proxyquire(
    './bar',
    {
        './foo': {
            default: () => {
                return 1;
            }
        }
    }
).default;

Unless you use import {foo} from './foo' in which case you replace default with foo. Also note that proxyquire will return the same esModule format so you need to get the default property from your import of ./bar.

With issues like these I find it helpful to do a console.log of what I'm getting to better get a handle on it.

bendrucker commented 8 years ago

Ah, good call! I vaguely remember Babel having a setting for export default --> module.exports but it's been more than a year since I've touched it.

jseminck commented 8 years ago

Is this documented somewhere?

I also couldn't get proxyquire to work with import/export syntax and was almost thinking to revert back to using require() syntax because of it. Luckily stumbled upon this thread and this solution works like a charm. (well thinking about it afterwards, it completely makes sense).

thlorenz commented 8 years ago

@jseminck we'll be happy to add some such section to the Readme. Could you please provide that addition via a PR? Thanks

jseminck commented 8 years ago

Sure. I'll try to write something about it with the examples from above. Not the best technical writer though. :)

Astridax commented 8 years ago

For reference to anyone else looking this is the plugin required to do this: https://www.npmjs.com/package/babel-plugin-add-module-exports

Source of info: http://stackoverflow.com/questions/33505992/babel-6-changes-how-it-exports-default