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

Node.js Jest测试中http模块未定义报错求助

解决Jest测试Node.js时Http模块undefined的问题

核心问题分析

你遇到的TypeError: Cannot read properties of undefined (reading 'createServer')错误,本质是代码里的http模块引用未被正确解析,导致其值为undefined。Node.js的http确实是内置模块,但在TypeScript + Jest的环境下,配置或代码写法的问题会导致模块无法正常加载。

具体解决方向

1. 修正Http模块的导入写法

Node.js内置模块是小写的http,不是大写的Http,先检查代码里的导入语句:

  • 正确的ES模块导入(TS环境):
    import * as http from 'http';
    // 启用esModuleInterop后可简化为:
    import http from 'http';
    
  • CommonJS写法(若TS配置为CommonJS):
    const http = require('http');
    

2. 确保TypeScript配置正确识别Node.js模块

  • 安装Node.js类型定义包:
    npm install @types/node --save-dev
    
  • 修改tsconfig.json关键配置:
    {
      "compilerOptions": {
        "module": "CommonJS", // 或NodeNext/ESNext,匹配你的模块系统
        "moduleResolution": "node",
        "types": ["node", "jest"] // 包含node类型,让TS识别内置模块
      }
    }
    

3. 检查Jest配置的测试环境

Jest默认测试环境是jsdom(用于浏览器代码),测试Node.js代码必须切换到node环境:

  • 在jest.config.js中配置:
    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'node',
      // 其他配置项...
    };
    
  • 或在package.json的jest字段中设置:
    {
      "jest": {
        "preset": "ts-jest",
        "testEnvironment": "node"
      }
    }
    

4. 排查错误的Mock操作

如果测试代码中使用了jest.mock('http')但未正确模拟模块导出,会导致http变为undefined。若不需要mock该模块,直接删除mock语句;若需要mock,需正确模拟方法:

jest.mock('http', () => ({
  createServer: jest.fn(() => ({
    close: jest.fn()
  }))
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 17:20:08