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

使用Jest和Axios编写API集成测试遇TLSWRAP句柄未关闭问题

解决Jest+Axios API测试的TLSWRAP句柄错误与授权失败问题

我用Jest和Axios编写API集成测试,之前把Bearer Token硬编码在PUT请求头里时测试正常运行,但调整后无法恢复可用状态,一直遇到Jest检测到TLSWRAP类型的未关闭句柄错误,导致测试无法正常退出,同时测试也无法成功返回200响应。

错误信息

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

● TLSWRAP

13 |
  14 |   it('user can create a cart', async () => {
> 15 |     const response = await axios.put(

已尝试的方案

  • 查阅Jest异步测试官方文档
  • 搜索并尝试相关的Jest未关闭句柄解决方案

当前测试代码

import axios from 'axios';

describe('Cart Manipulation', () => {
  let oc_token: string;

  beforeAll(() => {
    oc_token = "eyJblahblahblah"
  });

  it('user can create a cart', async () => {
    const response = await axios.put(
      'https://api.urltogoto',
      { 
        'Accept': 'application/json', 
        // 'Authorization': 'Bearer eyJblahblahblah'
        'Authorization': oc_token
      }
    );
    console.log(response);
    expect(response.status).toBe(200);
  });

});

解决方案

1. 修复授权头格式问题

你当前的Authorization头只传递了token字符串,但Bearer Token的标准格式需要前缀Bearer 。之前硬编码时是正确的,改用变量后漏掉了这个前缀,导致API无法识别授权信息,所以返回非200状态。

修改请求头部分:

{ 
  'Accept': 'application/json', 
  'Authorization': `Bearer ${oc_token}`
}

2. 解决TLSWRAP未关闭句柄问题

这个错误是因为Axios的HTTP/HTTPS连接池未关闭,导致Jest无法正常退出。可以通过销毁连接池来解决:

在测试套件中添加afterAll钩子,关闭Axios的连接代理:

describe('Cart Manipulation', () => {
  let oc_token: string;

  beforeAll(() => {
    oc_token = "eyJblahblahblah"
  });

  // 添加这个钩子销毁连接池
  afterAll(async () => {
    await axios.defaults.httpAgent.destroy();
    await axios.defaults.httpsAgent.destroy();
  });

  it('user can create a cart', async () => {
    const response = await axios.put(
      'https://api.urltogoto',
      { 
        'Accept': 'application/json', 
        'Authorization': `Bearer ${oc_token}`
      }
    );
    console.log(response);
    expect(response.status).toBe(200);
  });
});

如果使用了自定义Axios实例,需要销毁对应实例的agent:

const instance = axios.create({ /* 配置 */ });
// 测试后销毁
await instance.defaults.httpAgent.destroy();
await instance.defaults.httpsAgent.destroy();

若暂时需要快速验证,也可以给Jest添加--forceExit参数强制退出,但这只是临时方案,长期使用可能掩盖其他资源泄漏问题:
在package.json的测试脚本中修改:

"scripts": {
  "test": "jest --forceExit"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:41