Config 使用sinon模拟运行时配置值

Config 使用sinon模拟运行时配置值,config,sinon,proxyquire,Config,Sinon,Proxyquire,我正在hapi服务器启动之前添加一些配置值。虽然在测试中我不能使用config.get(),但应用程序运行良好。我可以和你在一起。所以我想知道 “动态”添加配置文件是错误的设计吗 有没有办法在这种情况下使用config.get() 有其他的方法吗 //initialize.js const config = require('config'); async function startServe() { const someConfigVal = await callAPIToGetS

我正在hapi服务器启动之前添加一些配置值。虽然在测试中我不能使用config.get(),但应用程序运行良好。我可以和你在一起。所以我想知道

  • “动态”添加配置文件是错误的设计吗
  • 有没有办法在这种情况下使用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);
      .....
    }
    
上下文:测试

  • “动态”添加配置文件是错误的设计吗?=>不,我以前做过。测试代码在测试中期更改配置文件:default.json,以检查测试中的函数是否按预期运行。我用了几个
  • 有没有一种方法可以在这种情况下使用config.get()对有关sinon的用法,请参见下面使用摩卡的示例。您需要在被测函数使用它之前定义存根/模拟,并且不要忘记恢复存根/模拟。还有与此相关的官方文件:,但未使用sinon
const config=require('config');
const sinon=要求(“sinon”);
const{expect}=require('chai');
//示例:正在测试的简单函数。
函数其他(){
const valFromConfig=config.get('dynamicValue.X');
返回valFromConfig;
}
描述('Config',函数(){
它('没有存根或模拟'),函数(){
//配置dynamicValue.X不存在。
//期望抛出错误。
试一试{
其他();
expect.fail('expect never get here');
}捕获(错误){
expect(error.message).to.equal('未定义配置属性“dynamicValue.X”);
}
});
它('使用存根获取'),函数(){
//创建存根。
const stubConfigGet=sinon.stub(配置“get”);
stubConfigGet.withArgs('dynamicValue.X')。返回(false);
//给我打电话。
常数测试=其他();
//验证测试结果。
期望(测试)等于(错误);
expect(stubConfigGet.calledOnce).to.equal(true);
//恢复存根。
stubConfigGet.restore();
});
它('get using mock'),函数(){
//创建模拟。
const mockConfig=sinon.mock(config);
mockConfig.expected('get').once().withArgs('dynamicValue.X')。返回(false);
//给我打电话。
常数测试=其他();
//验证测试结果。
期望(测试)等于(错误);
//恢复模拟。
expect(mockConfig.verify()).to.equal(true);
});
});
希望这有帮助