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

使用Jest测试React Native Fetch API时遇RequestContentLengthMismatchError错误

Expo Jest测试出现RequestContentLengthMismatchError错误

我有一个Expo应用,包含简单CRUD操作,应用运行正常,但用Jest编写测试场景时出现以下错误:

FAIL  apis/index.test.tsx
 Fetching Tests
× Should return correct user name (1561 ms)

● Fetching Tests › Should return correct user name

TypeError: fetch failed

Cause:
RequestContentLengthMismatchError: Request body length does not match content-length header

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        4.033 s
Ran all test suites.

我的测试代码如下:

describe("Fetching Tests", () => {
  it("Should return correct user name", () => {
    return SimpleCrudPersistence.addUser("ali", 12, "antalia").then((data) =>
      expect(data.name).toBe("ali")
    );
  }, 30000);
});

解决方向:

  1. 校验请求体与Content-Length一致性

    • 排查SimpleCrudPersistence.addUser内部的fetch逻辑:如果手动设置了Content-Length头,要确保其值和序列化后请求体的字节长度完全匹配。非ASCII字符会导致字符数和字节数不一致,需用new TextEncoder().encode(JSON.stringify(body)).length计算真实字节长度。
    • 若没有特殊需求,不要手动设置Content-Length,让浏览器/Node.js自动生成该头,避免计算错误。
  2. 用Mock替代真实API请求
    Jest测试不建议调用真实后端接口,直接mock目标方法即可完成测试:

    // 在测试文件顶部mock目标模块
    jest.mock('./path-to-SimpleCrudPersistence', () => ({
      addUser: jest.fn().mockResolvedValue({ name: 'ali' })
    }));
    
    describe("Fetching Tests", () => {
      it("Should return correct user name", async () => {
        const data = await SimpleCrudPersistence.addUser("ali", 12, "antalia");
        expect(data.name).toBe("ali");
        // 可额外验证方法调用参数
        expect(SimpleCrudPersistence.addUser).toHaveBeenCalledWith("ali", 12, "antalia");
      });
    });
    
  3. 更新依赖或Node.js版本
    该错误可能是Node.js fetch实现或Jest环境的兼容性问题,尝试升级Jest、@jest/environment或Node.js到稳定版本,看是否能解决问题。

  4. 检查请求体是否被意外修改
    确认发送请求前,没有中间件或其他代码修改请求体内容,导致实际发送的内容与计算Content-Length时的原始内容不一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 23:35:07