5

I have a test-setup with mocha, babel and node that is meant to test ecmascript 6 code.

Does anybody have any suggestions on how to mock away imports in the module under test?

Torleif
  • 2,334
  • 3
  • 27
  • 28
  • 1
    This doesn't really have anything to do with ES6, but with the module loader you are using. jest auto-mocks dependencies: http://facebook.github.io/jest/ – Felix Kling Oct 12 '15 at 22:04
  • @FelixKling It has everything to do with ES6. CommonJS is easy to mock with proxyquire, but it's more complicated to solve with ES6 imports. I know of a few solutions, but am still searching for a better one. I would like to reopen this question to see what solutions others have found. jest as you mentioned is one solution, but it might not be the perfect solution for everyone, and it didn't answer how to solve it with Mocha. – gregers Mar 03 '16 at 19:32
  • @FelixKling +1 for reopening. This question is not a nodejs question, rather it's an ES6 one. `require` and `import` works very differently. – atoth Apr 04 '16 at 12:07
  • @atoth: *"This question is not a nodejs question, rather it's an ES6 one."* Well, the question mentions node, but lets assume it does not. In that case, the question could not be answered. ES6 alone has *nothing* to do with module *loading*. Any reasonable solution will depend on the environment, since its the environment that handles the module loading. ES6 modules just add some syntax. With it come some restrictions, but it doesn't fundamentally change how modules are loaded. I'm reopening the question, but I'm worried that it may be more misguiding than useful. – Felix Kling Apr 04 '16 at 15:25
  • There are a few suggested solutions over at http://stackoverflow.com/q/27323031/242582 which should be able to work - I've suggested using a `import * as obj from 'dependencies'` strategy which works with Babel and I imagine should work fine with Mocha. – carpeliam Jul 16 '16 at 18:18

1 Answers1

1

Imports and exports in ES2015 are part of the language itself, and are designed to be statically analysable. They therefore cannot be manipulated at runtime, and that makes dynamic mocking impossible.

I would recommend that you take a look at implementing some form of lightweight dependency injection framework, or dynamic module resolver.

SystemJS could be a good choice for you as a universal module loader.

Hope that helps!

James Henry
  • 844
  • 6
  • 12