SinonStub函数观察者

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

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

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

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

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

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

SinnStub上有听众或观察员吗?

谢谢。

javascript typescript express chai sinon
1个回答
0
投票

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

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 |                   
----------|---------|----------|---------|---------|-------------------
© www.soinside.com 2019 - 2024. All rights reserved.