79404305

Date: 2025-02-01 02:01:18
Score: 0.5
Natty:
Report link

As @oligofren says, you need to intercept the loading of the module in your test script, because once that reference exists in your test there you can't change it. However, there is a package called rewire which allows you to intercept the normal import flow by creating a private getter and setter on the import, and thereby dynamically importing them for overriding.

Example from rewire:

// lib/myModule.js

var fs = require("fs"),
    path = "/somewhere/on/the/disk";

function readSomethingFromFileSystem(cb) {
    console.log("Reading from file system ...");
    fs.readFile(path, "utf8", cb);
}

exports.readSomethingFromFileSystem = readSomethingFromFileSystem;

And in your test module:

// test/myModule.test.js

var rewire = require("rewire");
    
var myModule = rewire("../lib/myModule.js");
    
var fsMock = {
    readFile: function (path, encoding, cb) {
        expect(path).to.equal("/somewhere/on/the/disk");
        cb(null, "Success!");
    }
};
myModule.__set__("fs", fsMock);

myModule.readSomethingFromFileSystem(function (err, data) {
    console.log(data); // = Success!
});
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @oligofren
  • Low reputation (1):
Posted by: Kellan