Stub private functions in an ES6 module

Craig Taub
2 min readAug 17, 2017

--

Local/private functions are always hard to test in isolation. This post explores the potential ways to solve that problem.

Lets say you have a module which looks like this.

+run.js:

function _one() {
// do something big
}
function run() {
return _one();
}
export {
_one,
run as default,
};

You want to test run() and _one() in isolation how can you do this using Sinon stubs?
The below will not work.

import * as run;
sinon.stub(run, ‘_one’) // => doesnt do anything...not same instance.
run.default();

You could swap to using a Class.

export default Class Run {
_one() {
// something big
}
thing() {
return this._one()
}
}

Now we are working off an instance and your test would look like this:

import Run;
run = new Run(); // <- 1 extra line...is that so bad?
sinon.stub(run, ‘_one’) // => stubbed !!
run.thing();

However swapping your nice ES6 module to a Class just for testing is a horrendous idea. Instead try making use of the “modular” side of modules.
i.e. split our function into a seperate module, its heavy after all.
+util.js

export function one() {
// something big
}

Now import it and run it from there.
+run.js

import { one } from './util';
export default function run() {
return one();
}

Now our test will look like (pseudo form):

run = proxyquire: { one: oneStub } // => can hand it a new dependent
run()

We can use proxyquire to stub the dependency and control and test everything about run.js. Next we will be able to do the same for one().

Modules are meant to be composable/isolated and encourage simple interfaces and interactions.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Craig Taub
Craig Taub

No responses yet

Write a response