javascript - 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 上是否有一些听众或观察者?
谢谢你。
解决方案
这是单元测试解决方案:
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 |
----------|---------|----------|---------|---------|-------------------
推荐阅读
- javascript - 检查数组是否在增加
- java - 我在 Java 中看到双重算术的意外和不受欢迎的行为
- ruby - 运行此代码时出现 Ruby rake 样式错误
- javascript - 在两个 React 组件之间拖放
- python - 构建 Python Flask 应用程序的 Docker 映像显示空白 REST 端点路由
- javascript - 是否有可能获取道具并将其作为参数传递给函数?
- javascript - 如何使用 Firebase Web 更新数据库和 UI
- python - 如何使用 Python Sklearn 在逻辑回归中修复“惩罚项应该为正”?
- reactjs - 如何根据用户输入的表单数据更改对象的值?
- android-studio - Android Studio 1.1.0 的 Gradle 同步失败