Search code examples
node.jsmockingmocha.jssinonsinon-chai

How to mock npm module with sinon/mocha


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?


Solution

  • 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.