首页 > 解决方案 > SinonStub 函数观察者

问题描述

我尝试通过 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 上是否有一些听众或观察者?

谢谢你。

标签: javascripttypescriptexpresschaisinon

解决方案


这是单元测试解决方案:

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

推荐阅读