To test exported function, you can simply import it. But what about non-exported functions? Well that’s easy too, thanks to Rewire!
Recently, I finally integrated unit testing into my startup project. I’ve settled with Jest
, I’ll speak more about this in a separate journal entry. While writing my test, I ran into a bit of a dilemma of trying to write unit tests for non-exported functions 😖
Contents
It’s super straightforward to test exported functions.
// utils.js
export function sayHi() {
return '👋';
}
And a unit test could be something like this:
// utils.test.js
import { sayHi } from './utils.js';
describe('sayHi', () => {
it('returns wave emoji', () => {
expect(sayHi()).toBe('👋');
});
});
Now, what if the function is not exported?
function saySecret() {
return '🤫';
}
Ah yikes, there is no way to test it! 🤷♀️
// utils.test.js
// ❌
import { saySecret } from './utils.js';
saySecret; // undefined
And then I discover this nifty package called Rewire
! Here’s their official description:
Rewire adds a special setter and getter to modules so you can modify their behaviour for better unit testing. You may
The second point is exactly what I needed!
Instead of using rewire
, I used a package called babel-plugin-rewire
. Which is essentially ES6 version of rewire
, so I can use import
. Here’s their description:
It is inspired by rewire.js and transfers its concepts to es6 using babel.
#javascript #testing #web-development #programming #developer