You need to enable JavaScript to run this app. 如何在Express的controller中mock已封装的axios调用以进行单元测试
优惠活动
大模型
产品
解决方案
定价
更多

如何在Express的controller中mock已封装的axios调用以进行单元测试

最高效的mock实现方案

核心思路

你已经完成了getAddressWithPostcode封装模块的测试,无需再重复mock axios底层逻辑,直接mock该封装模块 + 极简模拟Express的req/res/next对象即可。整个测试不需要启动Express服务、不需要发起真实HTTP请求,执行速度最快,用例编写成本最低。

具体实现(以Jest为例,内置mock能力无需额外依赖)

1. Mock依赖的地址查询封装模块

// 替换为你实际的模块导入路径
jest.mock('./utils/address', () => ({
  getAddressWithPostcode: jest.fn()
}))
const { getAddressWithPostcode } = require('./utils/address')
// 导入待测试的controller
const { findAddress } = require('./controllers/address')

2. 构造极简的req/res/next mock对象

// 根据你的Params类型调整mock参数即可
const mockReq = { params: { postCode: '100000', number: '1' } }
const mockRes = {
  send: jest.fn(),
  // 支持链式调用res.status().send()
  status: jest.fn().mockReturnThis()
}
const mockNext = jest.fn()

3. 分场景编写测试用例

场景1:正常返回地址数据,无状态码

test('正常返回地址数据时直接调用res.send返回结果', async () => {
  const mockAddress = { province: '北京', city: '北京市', detail: '某某街道1号' }
  getAddressWithPostcode.mockResolvedValue(mockAddress)

  await findAddress(mockReq, mockRes, mockNext)

  // 校验是否正确传递参数调用封装模块
  expect(getAddressWithPostcode).toHaveBeenCalledWith(mockReq.params)
  // 校验返回逻辑正确
  expect(mockRes.send).toHaveBeenCalledWith(mockAddress)
  expect(mockRes.status).not.toHaveBeenCalled()
})

场景2:返回带状态码的错误信息

test('返回带状态码的错误时调用对应status返回错误信息', async () => {
  const mockErrorReturn = { status: 404, data: { Message: '当前邮编不存在' } }
  getAddressWithPostcode.mockResolvedValue(mockErrorReturn)

  await findAddress(mockReq, mockRes, mockNext)

  expect(mockRes.status).toHaveBeenCalledWith(404)
  expect(mockRes.send).toHaveBeenCalledWith('当前邮编不存在')
})

场景3:捕获异常时调用next传递错误

test('抛出异常时调用next传递错误对象', async () => {
  const mockThrowError = new Error('服务调用失败')
  getAddressWithPostcode.mockRejectedValue(mockThrowError)

  await findAddress(mockReq, mockRes, mockNext)

  expect(mockNext).toHaveBeenCalledWith(mockThrowError)
})

方案优势

  • 测试和封装模块的边界完全隔离,不会耦合底层axios的逻辑,仅聚焦controller本身的分支校验
  • 所有mock都是轻量的纯函数对象,单测执行速度为毫秒级,远高于使用supertest等发起真实HTTP请求的测试方案
  • 用例编写成本极低,不需要额外处理axios的各种返回/异常场景,只需要模拟getAddressWithPostcode的返回值即可覆盖controller的所有逻辑分支

如果你使用Mocha等其他测试框架,把Jest的mock替换为Sinon的stub即可,核心逻辑完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 22:30:01