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

Jest测试React-Native上传Firebase Storage遇xhr2 Blob不支持错误

解决Jest测试Firebase Cloud Storage上传Uint8Array时的「Unsupported send() data [object Blob]」错误

问题分析

报错核心原因:你使用的xhr2库不支持发送Blob类型数据,而Firebase Storage的uploadBytes方法在Node.js环境(Jest运行在Node环境)中,会自动将传入的Uint8Array转换为Blob,导致xhr2无法处理并抛出错误。同时原测试代码未等待异步操作完成,Jest会在上传结束前提前终止测试,无法验证结果。

解决方案

方案1:替换为支持Blob的XMLHttpRequest实现

安装xmlhttprequest库(该库支持Node环境下发送Blob数据):

npm install xmlhttprequest --save-dev

在测试文件头部替换全局XMLHttpRequest:

global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;

方案2:将Uint8Array转为Node原生Buffer

直接利用Node.js原生Buffer类型(Firebase的uploadBytes方法原生支持Buffer),避免转换为Blob的过程,同时修正异步等待问题:

// Test upload file
test('Upload d un fichier', async () => {
   const storage = getStorage();
   const storageRef = ref(storage, 'some-child');
   
   const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x21]);
   // 将Uint8Array转为Node Buffer
   const uploadBuffer = Buffer.from(bytes);
   // 等待上传完成
   const snapshot = await uploadBytes(storageRef, uploadBuffer);
   console.log('Uploaded an array!');

   // 验证文件可正常检索
   const downloadedBuffer = await getBytes(storageRef);
   // 转换回Uint8Array进行断言
   expect(new Uint8Array(downloadedBuffer)).toEqual(bytes);
})

关键注意点

  • 必须使用async/await或返回Promise,确保Jest等待上传、下载的异步操作完成,否则测试结果不可靠。
  • 方案2无需额外安装依赖,贴合Node.js原生支持,推荐优先使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 15:53:21