目前,我的代码中有一个内存泄漏,我试图通过使用节点v8库创建堆快照来调试它。我正在使用express在类型记录中创建端点,我可以调用它,它应该返回一个JSON对象,该对象可以写到文件中并导入到chrome工具中。
但是,当我运行我的jest测试来测试端点时,它将无限期挂起。我正在打电话
jest --runInBand InfoController.test.tsInfoController.ts
import { Router } from 'express';
import { getHeapSnapshot } from 'v8';
import { constants } from 'http2';
export const InfoController = (): Router => {
const router = Router();
router.get('/heapdump', (_, res) => {
console.log('requesting heap snapshot')
const heapShot = getHeapSnapshot();
console.log('heap');
let data = '';
heapShot.on('readable', () => {
const chunk = heapShot.read();
while (chunk !== null) {
data += chunk;
}
});
heapShot.on('end', () => res.status(constants.HTTP_STATUS_OK).json(JSON.parse(data)));
});
return router;
};InfoController.test.ts
import express from 'express';
import { constants as httpConstants } from 'http2';
import Request from 'supertest';
import { InfoController } from './InfoController';
describe(' InfoController', () => {
describe('GET /heapdump', () => {
test('should be able to retrieve a v8 heapdump of the service', async () => {
const controller = InfoController();
const app = express();
app.use(express.json());
app.use(controller);
const result = await Request(app).get('/heapdump').expect(httpConstants.HTTP_STATUS_OK);
console.log(result.body);
});
});
});jest.config.js
module.exports = {
preset: 'ts-jest',
bail: true,
verbose: true,
testEnvironment: 'node',
collectCoverage: false,
testMatch: ['**/**/*.test.ts'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/build/'],
collectCoverageFrom: ['<rootDir>/src/**', '!<rootDir>/src/index.ts'],
coveragePathIgnorePatterns: ['<rootDir>/node_modules', '<rootDir>/__tests__'],
globalSetup: '<rootDir>/__tests__/global/setup.ts',
};这是我得到的输出
$ jest --runInBand src/http/controllers/InfoController.test.ts
console.log
requesting heap snapshot
at src/http/controllers/InfoController.ts:8:13
RUNS src/http/controllers/InfoController.test.ts在这之后,它只是挂着,永远不会完成?
发布于 2022-07-07 08:38:50
考虑一下代码中心的这个片段:
const chunk = heapShot.read();
while (chunk !== null) {
data += chunk;
}如果chunk永远是非空的(这几乎是肯定会发生的),那么这个循环将永远循环(或者,至少,直到data变得如此大,整个进程都会与OOM崩溃)。
正式文件展示了如何修改代码片段以使其工作的一种可能性:
let chunk;
while ((chunk = heapShot.read()) !== null) {
data += chunk;
}https://stackoverflow.com/questions/72890983
复制相似问题