Categories
JavaScript Answers

How to test private functions in unit tests with Mocha and Node.js?

Spread the love

Sometimes, we want to test private functions in unit tests with Mocha and Node.js.

In this article, we’ll look at how to test private functions in unit tests with Mocha and Node.js.

How to test private functions in unit tests with Mocha and Node.js?

To test private functions in unit tests with Mocha and Node.js, we can use the rewire module.

To install it, we run

npm i rewire

Then we use it by writing

const rewire = require("rewire");
const foobar = rewire("./foobar");

describe("private_foobar1", () => {
  const privateFoobar1 = foobar.__get__("privateFoobar1");

  it("should do stuff", (done) => {
    const stuff = privateFoobar1(filter);
    should(stuff).be.ok;
  });
});

to import the ./foobar module that we want to test.

And then we use __get__ to get the privateFoobar1 function from ./foobar.

Then we call the returned privateFoobar1 in our test.

Conclusion

To test private functions in unit tests with Mocha and Node.js, we can use the rewire module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *