【问题标题】:SinonStub function observerSinonStub 函数观察者
【发布时间】:2019-11-02 17:07:36
【问题描述】:

我尝试通过 sinon.js 测试 express 中间件

我想测试一下,它发送到响应特定的 JSON 并且不让请求转到下一个中​​间件或请求处理程序。

const middleware = (req: Request, res: Response, next: NextFunction) => {
  setTimeout(() => res.json({status: 'blocked'}), 1000);
}

对于模拟请求和响应,我使用sinon-express-mock。所以 Response 对象中的每个属性和方法都是SinonStub

我的问题是,当我调用中间件并调用方法json时,我不知道,调用后如何检查它。

SinonStub 上有没有监听器或观察器?

谢谢。

【问题讨论】:

    标签: javascript typescript express chai sinon


    【解决方案1】:

    这里是单元测试解决方案:

    index.ts:

    import { NextFunction, Response, Request } from 'express';
    
    const middleware = (req: Request, res: Response, next: NextFunction) => {
      setTimeout(() => res.json({ status: 'blocked' }), 1000);
    };
    
    export { middleware };
    

    index.test.ts:

    import { middleware } from './';
    import { Request } from 'express';
    import sinon, { SinonFakeTimers } from 'sinon';
    
    describe('56676480', () => {
      let clock: SinonFakeTimers;
      before(() => {
        clock = sinon.useFakeTimers();
      });
      after(() => {
        clock.restore();
      });
      it('should pass', () => {
        const mReq = {} as Request;
        const mRes = { json: sinon.stub() } as any;
        const mNext = sinon.stub();
        middleware(mReq, mRes, mNext);
        clock.tick(1000);
        sinon.assert.calledWithExactly(mRes.json, { status: 'blocked' });
      });
    });
    

    100% 覆盖率的单元测试结果:

      56676480
        ✓ should pass
    
    
      1 passing (12ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ----------|---------|----------|---------|---------|-------------------
    All files |     100 |      100 |     100 |     100 |                   
     index.ts |     100 |      100 |     100 |     100 |                   
    ----------|---------|----------|---------|---------|-------------------
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 2023-04-10
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多