Tuesday, November 10, 2015

Test friendly JavaScript modules - without Dependency Injection

A while ago, I was trying to figure out how to use test driven development with ES2015 (also known as ES6 at the time). It turned out to be a nice experience, and I wrote a blog post about it: Can I test it?

However, I had some concerns about the import feature and how to deal with module dependencies. I wrote a blog post about that too: Is the ES6 import feature an anti pattern?

Recently, I have been learning Python and was surprised by the similarities with JavaScript - in coding style, philosophy and language features. I guess Python has been a source of inspiration for the new ES2015 stuff. I have quickly become a fan of Python and I think it is a very nice language.

 At first, as a Python newbie, I stumbled upon the same questions on how to unit test modules containing a bunch of import statements. Luckily, at work I am surrounded with great programmers in general, that also are experts in the Python language. With Python, the answer to my questions was both simple and obvious. Python is a dynamic language: load the dependency in the unit test, then just override it. The code under test will use the already loaded in memory module. Simple, huh? It seems to me that there is no need for c#/java like dependency injections. I guess it was my typed language mindset that had guided me to IoC and DI patterns.

What about JavaScript?
I think it is (almost) as simple! Modules and imports in JavaScript are similar to (but not exactly like) the Python way. In JavaScript, I guess it also depends on the module loader used in the current environment. I have experimented with this. My setup contain ES2015 modules and unit tests, that are transpiled with Babel to RequireJS modules, runs in a browser or with PhantomJS. With this setup, I have managed to override module dependencies with fakes from a unit test. The module under test will actually run the fake dependency, and there is no need for custom Dependency Injection.

An example: a unit test
import foo from 'modules/foo';
import bar from 'modules/bar';

const fakeMessage = 'a fake message.';

const original = bar.getMessage;
const fake = () => fakeMessage;

QUnit.module('my example tests', {
    beforeEach() {
        bar.getMessage = fake;
    },
    afterEach() {
        bar.getMessage = original;
    }
});

QUnit.test('can an imported module be mocked?', assert => {
assert.equal(foo.message(), fakeMessage);
});

And the actual code under test:
import bar from 'modules/bar';

let foo = {
    message() {
        return bar.getMessage();
    }
};


export default foo;

I would appreciate your feedback on this!

You will find unit tests, code, settings, project structure and setup at my GitHub page:
https://github.com/DavidVujic/blog/tree/master/es2015-testable-modules