I'm trying to run a unit test on a non exported function using mocha, but it gives an error 'xx is not a function'. Sample structure is like the ff code, wherein I'd like to test the function isParamValid. The code format in settings.js already exists in our system so I cannot refactor it.
// settings.js
const settings = (() => {
const isParamValid = (a, b) => {
// process here
}
const getSettings = (paramA, paramB) => {
isParamValid(paramA, paramB);
}
return {
getSettings,
}
})();
module.exports = settings;
I've tried the ff code to test it, but mocha gives the error ReferenceError: isParamValid is not defined
// settings.test.js
const settings= rewire('./settings.js');
describe('isParamValid', () => {
it('should validate param', () => {
let demo = settings.__get__('isParamValid');
expect(demo(0, 1)).to.equal(true);
expect(demo(1, 0)).to.equal(true);
expect(demo(1, 1)).to.equal(false);
})
})
You can't directly access isParamValid
here. Try to test it via integration as below
const settings = require('./settings.js'); // No need of rewire
describe('isParamValid', () => {
it('should validate param', () => {
const demo = settings.getSettings; // Read it from getSettings
expect(demo(0, 1)).to.equal(true);
expect(demo(1, 0)).to.equal(true);
expect(demo(1, 1)).to.equal(false);
})
})