How to mock npm module with sinon/mocha
Asked Answered
Y

1

9

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?

Youngran answered 1/9, 2019 at 21:28 Comment(0)
P
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.

Perforation answered 1/9, 2019 at 21:33 Comment(3)
I've tried it. And I got that it was called 0 times.Youngran
@Youngran 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.Perforation
even i also getting the same 0 always.. not able to find what i have missed here :(Gilly

© 2022 - 2024 — McMap. All rights reserved.