【问题标题】:How to stub a JSON file with Sinon如何使用 Sinon 存根 JSON 文件
【发布时间】:2019-11-15 08:01:01
【问题描述】:

我有一个 JSON 文件,我需要以下方式:

const things = require('./path/to/things);

我想在沙箱中存根这个文件,所以它总是返回给定的夹具。


const fixture = {
  fake: "things"
}

const sandbox = sinon.createSandbox();

beforeEach(() => {
  sandbox.stub(things).returns(fixture);
});

afterEach(() => {
  sandbox.restore();
});

这会导致错误returns is not a function。我不确定如何使用沙箱存根 JSON。谁能帮帮我?

【问题讨论】:

    标签: tdd sinon


    【解决方案1】:

    您只能存根方法调用。在这种情况下,呼叫是require(...)。我认为你有两个选择:

    1. 存根 require 函数。

      const sinon = require('sinon');
      const Module = require('module');
      const sandbox = sinon.createSandbox();
      sandbox.stub(Module.prototype, 'require').returns({fake:'things'});
      const things = require('./things/');
      console.log(JSON.stringify(things));
      

      这是上面的repl链接:https://repl.it/repls/PessimisticSubtleHexagon

    2. 让你的被测系统依赖things并注入它。这样您就可以将要测试的逻辑与 import 语句分离。

    【讨论】:

    • 谢谢。我选择了依赖注入方法。
    【解决方案2】:

    另一种方法是使用proxyquire 允许require 语句返回模拟json。

    // noCallThru() is used to prevent call to the real JSON
    // @see https://github.com/thlorenz/proxyquire#preventing-call-thru-to-original-dependency
    
    const proxyquire = require('proxyquire').noCallThru();
    
    const fixture = {
      fake: "things"
    }
    
    const src = proxyquire('./source-file', { './path/to/things': fixture });
    
    beforeEach(() => {
      // empty
    });
    
    afterEach(() => {
     // empty
    });
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 2015-10-13
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2017-05-04
      相关资源
      最近更新 更多