【问题标题】:How can I stub an internal function in my route with sinon如何在我的路由中使用 sinon 存根内部函数
【发布时间】:2020-07-31 02:26:19
【问题描述】:

我有我的内部功能

//in greatRoute.ts
async function _secretString(param: string): Promise<string> {
   ...
}

router
  .route('/foo/bar/:secret')
  .get(
    async (...) => {
      ...
      const secret = _secretString(res.params.secret);
      ...
    },
  );

export default {
  ...
  _secretString
};

现在我正在尝试使用sinon.stub 模拟通话,如下所示:

sinon.stub(greatRoute, '_secretString').resolves('abc');

但这并不像我想要的那样工作。当我在测试中调用路由时,它仍然会进入_secretString 函数。我在这里错过了什么吗?我已经尝试将导出放在函数头的前面,如下所示: export async function _secretString(param: string): Promise&lt;string&gt; 而不是做export default {...},但这没有帮助。

【问题讨论】:

    标签: node.js typescript express sinon sinon-chai


    【解决方案1】:

    您可以使用rewire 包来存根_secretString 函数。例如

    index.ts:

    async function _secretString(param: string): Promise<string> {
      return 'real secret';
    }
    
    async function route(req, res) {
      const secret = await _secretString(req.params.secret);
      console.log(secret);
    }
    
    export default {
      _secretString,
      route,
    };
    

    index.test.ts:

    import sinon from 'sinon';
    import rewire from 'rewire';
    
    describe('61274112', () => {
      it('should pass', async () => {
        const greatRoute = rewire('./');
        const secretStringStub = sinon.stub().resolves('fake secret');
        greatRoute.__set__('_secretString', secretStringStub);
        const logSpy = sinon.spy(console, 'log');
        const mReq = { params: { secret: '123' } };
        const mRes = {};
        await greatRoute.default.route(mReq, mRes);
        sinon.assert.calledWithExactly(logSpy, 'fake secret');
        sinon.assert.calledWith(secretStringStub, '123');
      });
    });
    

    带有覆盖率报告的单元测试结果:

    fake secret
        ✓ should pass (1383ms)
    
    
      1 passing (1s)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |      75 |      100 |      50 |      75 |                   
     index.ts |      75 |      100 |      50 |      75 | 2                 
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 2016-05-11
      • 2018-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多