The v8 getHeapShot function is causing an infinite hang in jest

I am currently facing a memory leak issue in my code and I am attempting to troubleshoot it by generating a heap snapshot using the Nodes v8 library. I am developing an endpoint in typescript with express that can be invoked to retrieve a JSON object, which can then be saved to a file and imported into chrome dev tools.

However, when I execute my jest test to check the functionality of the endpoint, it gets stuck indefinitely. I am running

jest --runInBand InfoController.test.ts

InfoController.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',
};

This is the output I am seeing

$ 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

Following this, it just hangs indefinitely without completion ????

Answer â„–1

Take a look at this code snippet in the midst of your program:

      const block = stackTrace.check();
      while (block !== null) {
        information += block;
      }

If block is ever not null (which is highly likely), it will keep looping endlessly (or until information grows so large that the system crashes due to lack of memory).

The official guide offers a solution on how to adjust the snippet for it to function correctly:

  let block;
  while ((block = stackTrace.check()) !== null) {
    information += block;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`Is it possible to integrate npm libraries with typescript and ES6?`

I am looking to focus on using ES6 as the output for a node server-side app that I plan to run on the cutting-edge iojs distribution, which hopefully has support for the latest ES6 syntax. However, I'm unsure about how to integrate standard NPM libra ...

Unusual problem arises with scoping when employing typeguards

Consider the following TypeScript code snippet: interface A { bar: string; } const isA = <T>(obj: T): obj is T & A => { obj['bar'] = 'world'; return true; } let obj = { foo: 'hello' }; if (!isA(obj)) thro ...

TypeScript focuses on checking the type of variables rather than their instance

Is there a way to pass a type (not an instance) as a parameter, with the condition that the type must be an extension of a specific base type? For example abstract class Shape { } class Circle extends Shape { } class Rectangle extends Shape { } class ...

Determine the tuple data type by analyzing a union of tuples using a single element as reference

Looking for a way to work with a union of tuples: type TupleUnion = ["a", string] | ["b", number] | [Foo, Bar] // ... In need of defining a function that can handle any type K extends TupleUnion[0], with the return type being inferred ...

Data loss occurs when the function malfunctions

Currently, I am working with Angular version 11. In my project, I am utilizing a function from a service to fetch data from an API and display it in a table that I created using the ng generate @angular/material:table command. Client Model export interfac ...

Retrieving Vue component properties as a data type

I'm facing a dilemma with my Vue components. I want to extract the props from one component and use them as a type instead of a value in another component. Specifically, I have a component where I need to take in an array of props from a different com ...

Playwright failing to execute GraphQL tests due to TypeScript configuration problems

I'm facing an issue with my repo where I am running tests using Playwright against a graphQL URL. Despite configuring the tests, there is an error indicating that the environment variable defining the environment cannot be found. The repository in qu ...

What could be causing my React Redux state to not trigger a re-render?

Having trouble with my redux state not triggering a re-render when using a selector. I'm new to react-redux and typescript, and despite following advice online about returning a new object from the reducer, my object is still not re-rendering even tho ...

Using Angular/Typescript with @Output and Union return types

I have implemented several modal windows that allow users to select records from a paged list in the database. For example, there is a component called course.select.component.ts specifically for selecting courses. The modal window accepts an @Input() mul ...

Is it possible to execute TypeScript class methods in asynchronous mode without causing the main thread to be blocked?

Creating an app that retrieves attachments from specific messages in my Outlook mail and stores the data in MongoDB. The challenge lies in the time-consuming process of receiving these attachments. To address this, I aim to execute the task in a separate t ...

What is the process for defining a generic function to convert to an array in TypeScript?

Here is a versatile function that wraps any value into an array: const ensureArray = <T,>(value?: T | T[]): T[] => { if (Array.isArray(value)) return value if (value === undefined) return [] return [value] } const undef = undefined ensureAr ...

Using React MUI Select in combination with react-hook-form does not seem to be compatible with Cypress testing

Within my React application, I have implemented a form that includes a dropdown select. Depending on the option selected from the dropdown, different input fields are rendered. const [templateType, setTemplateType] = useState(""); const { regi ...

Is there a possibility of Typescript expressions `A` existing where the concept of truthiness is not the same as when applying `!!A`?

When working with JavaScript, it is important to note that almost all expressions have a "truthiness" value. This means that if you use an expression in a statement that expects a boolean, it will be evaluated as a boolean equivalent. For example: let a = ...

Responding to ipcMain events within Spectron

I created an electron application that initiates a launcher window (in a renderer process) first, which then starts multiple background services. Once these background services are successfully started, it sends the message "services-running" on its ipcRen ...

Angular 8: Implementing functionality for the Parent Component to detect when the User clicks outside of the Child Component Textbox

I am working on a scenario where I have a Parent Component and a Child Component containing a Formbuilder and a ZipCode textbox. Is there a way to notify the Parent Component when the user clicks out of the Child Component Textbox? I need to trigger some ...

Incorporate axios within getStaticProps while utilizing Next.js

I am working on a new project where I am utilizing axios to handle request data. However, I am facing an issue when using axios in the getStaticProps function which results in an error on my index.js page. Here is a snippet of my index.js code: import ...

Tips for saving an Angular project for offline use

I have created a basic form for a family member to use in their medical practice, and I want to make it functional offline. The form simply captures data and displays it, with no need to send or store the information anywhere. What would be the most effect ...

Leveraging the left-hand side operator while invoking functions within Angular 2 templates

I've encountered a puzzling situation with the function in my component : public limit: number = 3 public logLimit(limit) { console.log(limit) } and in my template : <div (click)="logLimit(--limit)">Decrease and log limit</div> Stra ...

Is the async pipe the best choice for handling Observables in a polling scenario

The situation at hand: I currently have a service that continuously polls a specific URL every 2 seconds: export class FooDataService { ... public provideFooData() { const interval = Observable.interval(2000).startWith(0); return interval ...

Guide to leveraging clsx within nested components in React

I am currently using clsx within a React application and encountering an issue with how to utilize it when dealing with mappings and nested components. For instance: return ( <div> <button onClick={doSomething}>{isOpened ? <Component ...