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

Jest自动模拟(automock)未成功模拟Axios的问题求助

解决Jest测试Axios代码时Authorization头为undefined的错误

你遇到的错误根源是测试环境中未配置process.env.token和process.env.url这两个环境变量,导致函数读取这些值时拿到undefined,进而让Axios请求的Authorization头变成无效值,触发了报错。

下面是具体的解决思路:

1. 手动在测试中设置环境变量

最简单的方式是直接在测试文件里给process.env赋值,确保函数能读取到合法的环境变量:

const axios = require('axios')
const { findUserById } = require('../../../src/functions/find-user-by-id')

jest.mock('axios')

// 在测试前初始化环境变量
process.env.url = 'https://test-api.example.com';
process.env.token = 'fake-test-authorization-token';

describe('findUserById', () => {
  it('should return null', async () => {
    axios.mockResolvedValue({
      data: {
        data: {},
      },
    })

    const user_id = 'non-valid-user-id'
    const user = await findUserById(user_id)

    // 修正断言:验证Axios是否被传入了正确的参数
    expect(axios).toHaveBeenCalledWith({
      method: 'get',
      baseURL: process.env.url,
      url: '/find-user',
      headers: {
        'Authorization': process.env.token,
        'id': user_id,
      },
    })
    expect(user).toBe(null)
  })
})

2. 使用dotenv加载测试环境变量

如果项目有专门的测试环境配置文件(比如.env.test),可以用dotenv包批量加载:
首先安装依赖:

npm install dotenv --save-dev

然后在测试文件顶部引入并加载配置:

// 加载测试环境变量文件
require('dotenv').config({ path: './.env.test' });

const axios = require('axios')
const { findUserById } = require('../../../src/functions/find-user-by-id')

jest.mock('axios')

// 后续测试逻辑不变
describe('findUserById', () => {
  // ...
})

另外注意:你原测试代码中的expect(axios).toHaveBeenCalledWith()是空断言,无法验证函数调用Axios的参数是否正确,建议替换成上面示例中的完整参数断言,这样能确保函数逻辑符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 19:09:29