使用sinon模拟运行时配置值

问题描述 投票:0回答:1

我在启动hapi服务器之前添加了一些配置值。应用程序工作正常,尽管在测试中我不能使用config.get()。我可以解决proxyquire。所以我想知道

  • 是否“动态”添加配置文件是错误的设计?
  • 有没有办法在这种情况下使用config.get()?
  • 是否有其他替代方法?

    //initialize.js
    
    const config = require('config');
    
    async function startServe() {
      const someConfigVal = await callAPIToGetSomeJSONObject();
      config.dynamicValue = someConfigVal;
      server.start(); 
    }
    
    //doSomething.js
    
    const config = require('config');
    
    function doesWork() {
      const valFromConfig = config.dynamicValue.X;
      // In test I can use proxiquire by creating config object
      ...
    }
    
    function doesNotWork() {
      const valFromConfig = config.get('dynamicValue.X'); 
      // Does not work with sinon mocking as this value does not exist in config when test run.
      // sinon.stub(config, 'get').withArgs('dynamicValue.X').returns(someVal);
      .....
    }
    
config sinon proxyquire
1个回答
0
投票

上下文:测试。

  • 是否“动态”添加配置文件是错误的设计? =>不,我以前做过。测试代码将更改配置文件:中期测试中的default.json,以检查被测函数是否按预期运行。我用了几个config utilities
  • 有没有办法在这种情况下使用config.get()? =>是的。有关sinon的用法,请参见下面的示例,该示例使用mocha。您需要在测试功能使用它之前定义存根/模拟,并且不要忘记还原存根/模拟。也有与此相关的官方文档:Altering configuration values for testing at runtime,但不使用sinon。
const config = require('config');
const sinon = require('sinon');
const { expect } = require('chai');

// Example: simple function under test.
function other() {
  const valFromConfig = config.get('dynamicValue.X');
  return valFromConfig;
}

describe('Config', function () {
  it ('without stub or mock.', function () {
    // Config dynamicValue.X is not exist.
    // Expect to throw error.
    try {
      other();
      expect.fail('expect never get here');
    } catch (error) {
      expect(error.message).to.equal('Configuration property "dynamicValue.X" is not defined');
    }
  });

  it('get using stub.', function () {
    // Create stub.
    const stubConfigGet = sinon.stub(config, 'get');
    stubConfigGet.withArgs('dynamicValue.X').returns(false);
    // Call get.
    const test = other();
    // Validate te result.
    expect(test).to.equal(false);
    expect(stubConfigGet.calledOnce).to.equal(true);
    // Restore stub.
    stubConfigGet.restore();
  });

  it('get using mock.', function () {
    // Create mock.
    const mockConfig = sinon.mock(config);
    mockConfig.expects('get').once().withArgs('dynamicValue.X').returns(false);
    // Call get.
    const test = other();
    // Validate te result.
    expect(test).to.equal(false);
    // Restore mock.
    expect(mockConfig.verify()).to.equal(true);
  });
});

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.