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

Node.js调用TestRail API上传测试截图失败问题求助

TestRail API 文件上传(Node.js Got库)正确实现方式

你遇到的问题核心在于:Python的requests库会自动将files参数封装为multipart/form-data格式的请求,但Got库需要你手动处理这种格式的请求体,不能直接把文件流或Buffer作为普通body传入。

正确实现方案(推荐用form-data库)

TestRail的文件上传API要求请求必须是multipart/form-data类型,且文件字段名固定为attachment。我们可以用form-data库来自动构建符合要求的请求体:

  1. 先安装依赖:
npm install form-data
  1. 实现上传代码:
const got = require('got');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

async function uploadTestRailAttachment(resultId, screenshotPath) {
  // 构建form表单
  const form = new FormData();
  // 添加文件流,必须指定文件名(TestRail依赖文件名识别类型)
  form.append('attachment', fs.createReadStream(screenshotPath), {
    filename: path.basename(screenshotPath)
  });

  try {
    const auth = Buffer.from('你的TestRail用户名:你的TestRail密码').toString('base64');
    const response = await got.post(
      `https://example.testrail.io/index.php?/api/v2/add_attachment_to_result/${resultId}`,
      {
        headers: {
          ...form.getHeaders(), // 自动生成multipart/form-data的必要headers(含boundary)
          Authorization: `Basic ${auth}`
        },
        body: form // 将form实例作为请求体,Got会自动处理流式上传
      }
    );

    return JSON.parse(response.body);
  } catch (err) {
    console.error('上传失败:', err.response?.body || err.message);
    throw err;
  }
}

// 调用示例
uploadTestRailAttachment(123456, '/cypress/screenshots/test.spec.js/测试用例名.png');

为什么之前的方式报错?

你之前直接将文件流或Buffer作为body传入Got,Got会把它当成普通的请求体(比如application/json或text/plain),但TestRail API只接受multipart/form-data格式的文件上传请求,因此触发了RequestError。

注意事项

  • 认证必须用Basic Auth:将用户名和密码用:拼接后转成Base64字符串
  • 必须指定文件名:TestRail需要通过文件名后缀识别文件类型(比如.png)
  • 确保文件路径正确:Cypress的截图默认路径是cypress/screenshots/[测试文件]/[用例名].png,注意动态获取路径

内容的提问来源于stack exchange,提问作者im-not-you

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 02:34:52