繁体   English   中英

如何在我的路由中使用 sinon 存根内部 function

[英]How can I stub an internal function in my route with sinon

我有我的内部 function

//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 function。 我在这里错过了什么吗? I already tried to put the export in front of the function header like this: export async function _secretString(param: string): Promise<string> instead of doing the export default {...} but that didn't help.

您可以使用将 package重新连接到存根_secretString function。 例如

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                 
----------|---------|----------|---------|---------|-------------------

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM