Retta
Retta

Reputation: 81

Proxyquire not stubbing

I'm trying to get Proxyquire to work with a simple method substitution but I can't figure out what I'm doing wrong.

I create lib.js

module.exports = {
    thing: () => {
        console.log("thing");
    }
};

And test.js

const lib = require("./lib");

module.exports = () => {
    lib.thing();
};

And the and attempted to stub the dependency and replace thing with another function ie

const proxyquire = require("proxyquire");
const libStub = {};
const test = proxyquire("./test", {"lib": libStub});

test();

libStub.thing = () => {
    console.log("replaced");
};

test();

But test is logging out "thing" both times instead of "replaced" on the second call. Any help is appreciated.

Upvotes: 2

Views: 2081

Answers (2)

Anton  Korzunov
Anton Korzunov

Reputation: 140

The best way to solve this issue, as long you will face it many times in the future is to use:

Both will throw an exception in case they fail to mock something with extract reason and extract file names they tried to use.

Upvotes: 0

jujule
jujule

Reputation: 11531

in proxyquire, use the same path that you use in the require itself :

so should be :

const proxyquire = require("proxyquire");
const libStub = {
  thing: () => console.log('replaced')
};
const test = proxyquire("./test", {"./lib": libStub});
test();

Upvotes: 5

Related Questions