Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock dependencies for unit tests with ES6 Modules

I'm trying to fiddle with Ecmascript 6 modules using webpack + traceur to transpile to ES5 CommonJS, but I'm having trouble successfully unit testing them.

I tried using Jest + traceur preprocessor, but the automocking and dependency names seem to get screwy, plus I can't seem to get sourceMaps to work with Jest and node-inspector debugging.

Is there a better framework to unit test ES6 modules?

like image 972
Evan Layman Avatar asked Dec 05 '14 19:12

Evan Layman


People also ask

Should unit test mock dependencies?

Correct. You should mock things that depend on anything persistent or external in order to prevent the test from depending on anything persistent or external.

Does jest support ES6 modules?

Jest will enable compilation from ECMAScript modules to CommonJS automatically, without having to inform additional options to your jest property inside package. json .

Is mocking a dependency injection?

Dependency injection is a way to scale the mocking approach. If a lot of use cases are relying on the interaction you'd like to mock, then it makes sense to invest in dependency injection. Systems that lend themselves easily to dependency injection: An authentication/authorization service.


1 Answers

I've started employing the import * as obj style within my tests, which imports all exports from a module as properties of an object which can then be mocked. I find this to be a lot cleaner than using something like rewire or proxyquire or any similar technique.

I can't speak for traceur which was the framework used in the question, but I've found this to work with my setup of Karma, Jasmine, and Babel, and I'm posting it here as this seems to be the most popular question of this type.

I've used this strategy most often when needing to mock Redux actions. Here's a short example:

import * as exports from 'module-you-want-to-mock'; import SystemUnderTest from 'module-that-uses-above-module';  describe('your module', () => {   beforeEach(() => {     spyOn(exports, 'someNamedExport');  // mock a named export     spyOn(exports, 'default');          // mock the default export   });   // ... now the above functions are mocked }); 
like image 66
carpeliam Avatar answered Sep 19 '22 06:09

carpeliam