如何测试中间件返回的request对象中挂载的请求属性值
问题核心原因
你的getProfit是工厂函数,不是直接的Express中间件:它执行内部逻辑(axios请求、更新profit变量)后,才会返回真正的中间件函数,你之前的调用逻辑完全错了。
修正步骤
1. 先补全原getProfit的可测试写法
你原代码里的异步axios请求没做等待处理,必须加async修饰,否则profit还没更新就返回中间件,值永远是0:
// 原业务文件正确写法 const axios = require('axios') async function getProfit() { let profit = 0; // 补全axios异步请求逻辑,加await等待返回 const apiRes = await axios.get('你的业务接口地址') profit = apiRes.data return (req, res, next) => { req.properties = { profit, }; next(); }; } module.exports = { getProfit, };
2. 修正测试代码
你存在2个测试逻辑错误:
req是普通对象,不是函数,不需要用jest.fn()定义- 中间件会直接修改你传入的req对象,不需要从返回值里拿属性,直接读你自己定义的req变量即可
修正后的测试代码:
const sinon = require('sinon'); const axios = require('axios'); const properties = require('../../middleware/properties'); describe('Properties Middleware', () => { let sandbox; beforeEach(() => { sandbox = sinon.createSandbox(); }); afterEach(() => { sandbox.restore(); }); it('should return the profit value in request', async () => { const mockProfit = 100; sandbox.stub(axios, 'get').resolves({ data: mockProfit }); // 1. 先调用getProfit拿到中间件函数,await等待内部axios执行完成 const profitMiddleware = await properties.getProfit(); // 2. 定义req为普通对象 const req = {} const res = { sendStatus: jest.fn() } const next = jest.fn(); // 3. 执行中间件函数,传入req/res/next profitMiddleware(req, res, next); // 4. 直接读取自定义req对象的属性即可 expect(req.properties.profit).toEqual(mockProfit); // 额外断言确保中间件逻辑完成后触发了next expect(next).toHaveBeenCalled() }); });
内容的提问来源于stack exchange,提问作者samjo
相关产品推荐
相关产品推荐

