You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jest测试Express受保护接口时跳过auth中间件,req.token未定义问题求助

问题原因

1. 中间件注册顺序错误

Express 中的中间件、路由是严格按照注册先后顺序执行的,你当前的代码先挂载了/private前缀的业务路由,之后才注册auth校验中间件:

// 先挂载业务路由,请求到这里就匹配到控制器直接执行了
testapp.use('/private', mappedPrivateRoutes);
// 这行auth中间件永远不会被匹配到的请求触发
testapp.all('/private/*', (req, res, next) => auth(req, res, next));

你本地正常启动服务时,必然是先注册auth中间件再挂载私有路由,所以Postman请求可以正常校验,测试代码的注册顺序写反了才导致中间件被跳过。

2. 测试用例变量名错误

你在beforeAll中把express实例赋值给了test_api变量,但发请求时调用的是request(api),api属于未定义变量,也会导致请求异常。

3. 路由配置漏写require(可选排查项)

你配置私有路由的代码漏了require:

// 错误写法,拿到的是字符串,不是路由配置对象
const privateRoutes = ('../routes/private_routes')
// 正确写法
const privateRoutes = require('../routes/private_routes')

修复方案

修改setupAction的中间件注册顺序,先注册auth校验,再挂载业务路由:

const setupAction = async () => {
  const testapp = express();
  const mappedPrivateRoutes = mapRoutes(privateRoutes, 'api/controllers/');

  testapp.use(express.urlencoded({ extended: false }));
  testapp.use(express.json());

  // 先注册auth中间件,所有/private前缀的请求先过校验
  testapp.use('/private', auth);
  // 校验通过再进入业务路由
  testapp.use('/private', mappedPrivateRoutes);

  return testapp;
};

再修正测试用例的请求变量:

test('Customer | get profile', async () => {
  let token = 'TestToken123'
  // 用你初始化的test_api变量发请求
  res = await request(test_api)
    .get('/private/customer/get-profile')
    .set('Accept', /json/)
    .set('Authorization', `Bearer ${token}`)
    .send()
    .expect(200);
  expect(res.body.customer_id).toBeTruthy();
});

修改后重新运行测试,auth中间件就可以正常执行了。

内容的提问来源于stack exchange,提问作者GAURAV KUMAR JHA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:36:05