nodejs override a function in a module

From outside a module's code, you can only modify that module's exports object. You can't "reach into" the module and change the value of function_b within the module code. However, you can (and did, in your final example) change the value of exports.function_b.

If you change function_a to call exports.function_b instead of function_b, your external change to the module will happen as expected.


You can actually use the package rewire. It allows you to get and set whatever was declared in the module

foo.js

const _secretPrefix = 'super secret ';

function secretMessage() {
    return _secretPrefix + _message();
}

function _message() {
    return 'hello';
}

foo.test.js

const rewire = require('rewire');

// Note that the path is relative to `foo.test.js`
const fooRewired = rewire('path_to_foo');

// Outputs 'super secret hello'
fooRewired.secretMessage();

fooRewired.__set__('_message', () => 'ciao')

// Outputs 'super secret ciao'
fooRewired.secretMessage();

Tags:

Node.Js