How to mock npm module with sinon/mocha

这一生的挚爱 提交于 2021-01-27 06:41:02

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/57749627/how-to-mock-npm-module-with-sinon-mocha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!