Sometimes, we want to unit test a Node.js module that requires other modules and how to mock the global require function.
In this article, we’ll look at how to unit test a Node.js module that requires other modules and how to mock the global require function.
How to unit test a Node.js module that requires other modules and how to mock the global require function?
To unit test a Node.js module that requires other modules and how to mock the global require function, we can use proxyquire
.
To install it, we run
npm i proxyquire
Then we use it by writing
const proxyquire = require("proxyquire");
const assert = require("assert");
const pathStub = {};
//...
const foo = proxyquire("./foo", { path: pathStub });
assert.strictEqual(foo.bar("file.txt"), ".TXT");
to call proxyquire
with the path to the module.
Then we call foo.bar
from the foo
module and check its returned value.
Conclusion
To unit test a Node.js module that requires other modules and how to mock the global require function, we can use proxyquire
.