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

Loopback 4中如何模拟Request对象实现控制器单元测试

解决方案

错误原因

createStubInstance 只会生成包含类自身原型方法的空存根,不会自动补全Express Request类型内置的数十个属性和继承方法,所以会触发TS类型不匹配报错。

实现方案

你不需要完整实现所有Request属性,只需要根据你的控制器实际用到的字段构造模拟对象,再通过类型断言绕开校验即可,示例代码如下:

首先导入依赖:

import { Request } from '@loopback/rest';
import { createStubInstance } from '@loopback/testlab';
import sinon from 'sinon';
// 导入你自己的控制器、服务
import { YourController } from './your-controller';
import { HttpService, LocalRequestService } from './your-services';

构造模拟对象并实例化控制器:

// 仅构造你的控制器实际用到的Request属性/方法即可
const mockRequest = {
  // 示例:如果你用到了headers、query、get方法,就按需添加
  headers: {
    authorization: 'Bearer test_token_123',
    'user-agent': 'test-agent'
  },
  query: {
    page: '1',
    size: '10'
  },
  params: {
    id: 'test_id'
  },
  get: sinon.stub().returns('test-value'),
  header: sinon.stub().withArgs('x-forwarded-for').returns('127.0.0.1')
} as unknown as Request; // 类型断言绕开TS全量属性校验

// 其他依赖用createStubInstance正常模拟即可
const httpServiceStub = createStubInstance(HttpService);
const localRequestServiceStub = createStubInstance(LocalRequestService);

// 实例化控制器
const controller = new YourController(
  mockRequest,
  httpServiceStub,
  localRequestServiceStub
);

可选补充

如果你的控制器用到了大量Request原生方法,不想逐个手动声明,可以引入mock-express-request包生成完整的模拟Request实例,再用sinon对需要的方法做存根即可,同样需要加类型断言适配Loopback的Request类型。

内容的提问来源于stack exchange,提问作者piccy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:15:07