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

NestJS项目中Jest运行时堆内存占用过高(达4GB)问题求助

NestJS项目中Jest运行时堆内存占用过高(达4GB)问题求助

我正在用NestJS框架开发项目,尝试用--runInBand参数串行运行单元测试,但不管测试内容是什么,堆内存居然占用了将近4GB,这完全超出我的预期。

更奇怪的是,我用命令node --no-compilation-cache --inspect-brk -r node_modules/.bin/jest --runInBand apps/events/src/events.controller.spec.ts启动测试时,发现甚至在globalSetup初始化之前,内存就已经占到4GB了,实在搞不懂原因!

以下是我的相关配置文件和测试用例:

jest.config.ts

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
  testMatch: ['**/*-test.ts', '**/**spec.ts', '.*\\.spec\\.ts$'],
  globalSetup: './spec/jest.setup.ts',
  globalTeardown: './spec/teardown.js',
  reporters: ['default', 'jest-junit'],
  moduleNameMapper: {
    '^apps/(.*)$': '<rootDir>/apps/$1',
    '^common/(.*)$': '<rootDir>/common/$1'
  },
  setupFilesAfterEnv: ['<rootDir>/spec/jest.setup.redis-mock.ts', '<rootDir>/apps/events/jest.setup.ts'],
  moduleFileExtensions: ['js', 'json', 'ts'],
  modulePaths: ['<rootDir>'],
  rootDir: '.',
  transform: {
    '^.+\\.(t|j)s$': [
      'ts-jest',
      {
        diagnostics: false
      }
    ]
  },
  collectCoverageFrom: ['**/*.(t|j)s'],
  coverageDirectory: './coverage',
  roots: ['<rootDir>', '<rootDir>/apps/'],
  testPathIgnorePatterns: [
    '/node_modules/',
    '/dist/'
  ]
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2020",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "paths": {
      "apps/*": [
        "./apps/*"
      ],
      "common/*": [
        "./common/*"
      ]
    },
    "resolveJsonModule": true
  }
}

测试用例:apps/events/events.controller.spec.ts

// import { Test, TestingModule } from '@nestjs/testing'
// import { EventsController } from './events.controller'

describe('EventsController', () => {

  describe('root', () => {
    it('should return "Hello World!"', () => {
      expect(true).toBe(true)
    })
  })
})

这个测试用例非常基础,按理说根本不需要占用这么多内存。

我的node_modules文件夹大小有2.2GB,我怀疑是不是测试初始化阶段就加载了所有依赖包?如果是这样的话,有没有什么优化方法可以降低内存占用呢?

备注:内容来源于stack exchange,提问作者suvodipMondal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 12:08:03