Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 960
Ndx Avatar asked Sep 01 '19 21:09

Ndx


1 Answers

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.

like image 156
Mickael B. Avatar answered Sep 22 '22 15:09

Mickael B.