8

I'm trying to test a function that calls the module cors. I want to test that cors would be called. For that, I'd have to stub/mock it.

Here is the function cors.js

const cors = require("cors");

const setCors = () => cors({origin: 'http//localhost:3000'});
module.exports = { setCors }

My idea of testing such function would be something like

cors.test.js

  describe("setCors", () => {
    it("should call cors", () => {
      sinon.stub(cors)

      setCors();
      expect(cors).to.have.been.calledOnce;

    });
  });

Any idea how to stub npm module?

Ndx
  • 517
  • 2
  • 12
  • 29

1 Answers1

5

You can use mock-require or proxyquire

Example with mock-require

const mock = require('mock-require')
const sinon = require('sinon')

describe("setCors", () => {
  it("should call cors", () => {
    const corsSpy = sinon.spy();
    mock('cors', corsSpy);

    // Here you might want to reRequire setCors since the dependancy cors is cached by require
    // setCors = mock.reRequire('./setCors');

    setCors();
    expect(corsSpy).to.have.been.calledOnce;
    // corsSpy.callCount should be 1 here

    // Remove the mock
    mock.stop('cors');
  });
});

If you want you can define the mock on top of describe and reset the spy using corsSpy.reset() between each tests rather than mocking and stopping the mock for each tests.

Mickael B.
  • 4,755
  • 4
  • 24
  • 48
  • 3
    I've tried it. And I got that it was called 0 times. – Ndx Sep 01 '19 at 21:47
  • @Ndx try `setCors = mock.reRequire('.path/to/setCors')`, as I wrote in the comment, modules are cached by `require` so if your `setCors` module was required before you try to mock `cors` then you'll need to reRequire it. – Mickael B. Sep 01 '19 at 21:52
  • even i also getting the same 0 always.. not able to find what i have missed here :( – Arundev Dec 01 '20 at 09:44