I’ve been trying to mock module dependencies with known require Npm override packages to no avail.
I would prefer this route as opposed to using dependency injection in my modules which would require a big rewrite of most of them and changes in my coding style.
This is a list of some packages I tried: "mock-require": "^3.0.1", "mockery": "^2.1.0", "proxyquire": "^1.8.0", "rewire": "^3.0.2", "rewiremock": "^3.4.2",
When using them either dependencies have not been mocked or the modules depended on could not be found when using relative paths while trying to mock them.
They weren’t even external dependencies just other modules I wrote which I imported to the module under test with an absolute (meteor) path similar to import moduleDependency from '/imports/api/<moduleDependencyPath>'
When using these absolute meteor paths the mocking would never work. And when trying to use relative paths the modules depended on would not be found to be mocked.
I am aware my ES6 imports are being transformed to CommonJS modules with Babel but I don’t know how this would affect the path which has to be provided to be overridden.
I am aware that most of these packages stress that they require the path provided to be overridden has to be relative to the module under test.
Has anyone been successful in using any of these packages or similar to mock dependecies of modules they are testing with meteor test?
Just fyi I am currently on version 1.6.0.1 and I don’t know if 1.6.1 would offer any benefits with Babel 7.
The idea behind it is straightforward, everything your service uses, gets injected via constructor, or a setter, or property, it doesn’t depend on modules (but it may depend on interfaces), and you instantiate your service elsewhere with the proper dependencies, this lets you properly test your Service, by instantiating and injecting your mocks in the test, and not relying on imports.
Thanks for your tips @diaconutheodor, as stated I dislike DI because it would require me to rewrite most of my modules.
I have not found a working approach for me and therefore would hugely appreciate anyone with an alternative approach to mocking dependencies or dependency injection.
@coagmano yes I had success with mocking Meteor with jest, but then I went with DI because it just felt cleaner. You’ll have to do some digging but it’s possible, I know I did it.
Just reporting back:
I don’t know what I was doing wrong at first, but importing and mocking the dependency with sinon worked perfectly without needing any dependency injection or setup.
Hey @coagmano, been having a lot of trouble trying to spy/stub/mock using sinon and meteor, do you have a sample code on how to achieve it? been trying for the last week and so far I cannot make it work.