【问题标题】:How to mock npm module with sinon/mocha如何用 sinon/mocha 模拟 npm 模块
【发布时间】:2019-09-01 21:28:32
【问题描述】:

我正在尝试测试调用模块cors 的函数。我想测试是否会调用cors。为此,我必须对它进行存根/模拟。

这里是函数 cors.js

const cors = require("cors");

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

我测试这种功能的想法是这样的

cors.test.js

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

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

    });
  });

知道如何存根 npm 模块吗?

【问题讨论】:

    标签: node.js mocking mocha.js sinon sinon-chai


    【解决方案1】:

    您可以使用mock-requireproxyquire

    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');
      });
    });
    
    

    如果您愿意,您可以在 describe 之上定义模拟,并在每个测试之间使用 corsSpy.reset() 重置间谍,而不是模拟和停止每个测试的模拟。

    【讨论】:

    • 我试过了。我知道它被调用了 0 次。
    • @Ndx 尝试setCors = mock.reRequire('.path/to/setCors'),正如我在评论中所写,模块由require 缓存,因此如果在您尝试模拟cors 之前需要您的setCors 模块,那么您将需要重新要求它。
    • 即使我也总是得到相同的 0.. 无法找到我在这里错过的东西 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 2018-08-28
    • 2016-10-11
    • 2019-11-14
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多