如何使用Sinon重构该Express中间件测试用例?
使用Sinon重构Express中间件测试用例
没问题,我来帮你把这个测试用例用Sinon重构得更简洁健壮!先看看你原来的测试代码——你用闭包数组val来追踪res.send的调用,虽然能跑,但需要手动维护额外状态,用Sinon可以完全摆脱这种方式:
it('should return html', async () => { const val = [] const req = {} const res = {send: (recieved) => {val.push(recieved)}} const next = (e) => {throw e} expect(val).to.be.length(0) await expressMiddleware(alpha)(req, res, next) const expectation = 'response sent' expect(val).to.be.length(1) expect(val[0]).to.be(expectation) })
重构方案
1. 先确保安装了Sinon
如果还没装,先执行:
npm install sinon --save-dev
2. 引入Sinon并重构测试用例
在测试文件顶部引入Sinon后,就可以用它的**存根(stub)**来模拟回调函数,直接断言调用行为,不需要额外维护状态变量:
const sinon = require('sinon'); it('should return html', async () => { // 用Sinon创建res.send的存根,替代手动写的push逻辑 const req = {}; const res = { send: sinon.stub() }; // 模拟next函数的抛出行为,同样用Sinon stub实现 const next = sinon.stub().throws(); // 执行中间件 await expressMiddleware(alpha)(req, res, next); // 直接断言存根的调用情况,逻辑更直观 const expectation = 'response sent'; expect(res.send.calledOnce).to.be.true; // 验证send被调用了一次 expect(res.send.calledWithExactly(expectation)).to.be.true; // 验证调用参数完全匹配 });
重构后的优势
- 去掉了冗余的
val数组,测试逻辑更聚焦于中间件的行为本身 - Sinon提供了丰富的断言方法:比如
calledTwice、calledWith、callOrder等,能轻松应对更复杂的测试场景 - 存根可以灵活配置行为(比如模拟抛出错误、返回特定值),比手动写回调更灵活
内容的提问来源于stack exchange,提问作者ThomasReggi
相关产品推荐
相关产品推荐

