I am just getting started unit testing nodejs. I have been using mocha, chai and sinon.
I hit a snag when I wanted to test a function which is not exported. proxyquire looks good, as does rewire.
There are lots of tutorials, but they tend to be simplistic. E.g
// Software under test
function saySecret() { // this function is *not* exported
return '';
}
// Unit test file
import utilsRewire from './utils.js';
describe('saySecret', () => {
it('returns shh emoji', () => {
const saySecret = utilsRewire.__get__('saySecret'); // the secret sauce
expect(saySecret()).toBe('');
});
});
While that is nice, I want to be able to force the function saySecret to return a specific value. The reason being that the function is called by a function which is exported, and I want to unit test the outer function, forcing it down failure paths.
How can I do that with sinon/proxyquire/rewire?
The API rewiredModule.set(name: String, value: *): Function of
rewirepackage can do this.E.g.
index.ts:index.test.ts:Test result: