Jest has identified a single open handle that may be preventing Jest from exiting: TCPSERVERWRAP

Currently, I am conducting a basic end-to-end testing procedure which seems to be failing at the moment. The primary issue I am facing is being unable to resolve an open handle.

A result of running all test suites reveals that Jest has identified one open handle that may prevent Jest from exiting:
  
  ● TCPSERVERWRAP

      40 |     }
      41 |     return request(app.getHttpServer())
    > 42 |       .post('/graphql')
         |        ^
      43 |       .send(mutation)
      44 |       .expect(HttpStatus.OK)
      45 |       .expect((response) => {

      at Test.Object.<anonymous>.Test.serverAddress (../node_modules/supertest/lib/test.js:61:33)
      at new Test (../node_modules/supertest/lib/test.js:38:12)
      at Object.obj.<computed> [as post] (../node_modules/supertest/index.js:27:14)
      at Object.<anonymous> (app.e2e-spec.ts:42:8)
import { Test, TestingModule } from '@nestjs/testing'
import { HttpStatus, INestApplication } from "@nestjs/common";
import * as request from 'supertest'
import { AppModule } from '../src/app.module'

describe('AppController (e2e)', () => {
  let app: INestApplication

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
  })

  afterAll(async () => {
    await app.close()
  })

  it('/ (GET)', () => {
    return request(app.getHttpServer())
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

  it('mutation', async () => {
    const mutation = {
      query: `mutation Create($title: String!) {
        create(title: $title) {
          id,
          title
        }
      }`,
      variables: {
        title: 'Mon programme',
      },
    }
    return request(app.getHttpServer())
      .post('/graphql')
      .send(mutation)
      .expect(HttpStatus.OK)
      .expect( (response) => {
        expect(response.body).toBe({
          id: expect.any(String),
          title: 'Mon programme',
        })
      })
  })
})

Can anyone help identify what might be causing the obstruction in the test runner?

It is worth noting that I am utilizing NestJs and therefore should not require the use of the .end(done) method at the conclusion of the test.

P.S.: It appears there is an excess of code provided in this question, but I am unsure what additional details could be included.

Answer №1

I have not yet discovered the ideal solution, but for now I have decided to use this workaround :

jest --config ./test/jest-e2e.json --forceExit

The --forceExit option helps terminate openHandles and resolve any lingering issues. However, I am still in search of the "correct way" to address this problem.

Answer №2

This is the issue at hand

  it('/ (GET)', () => {
    return request(app.getHttpServer())
                  ^^^^^^^^^^^^^^^^^^^^^
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

The problem lies in not closing the server after the test, leading it to remain open. To solve this, you should create a variable to hold the instance and close it after each test. It took me some time to figure this out, and I hope it helps others facing similar challenges.

Below is an example of your code with my suggested fix:

describe('AppController (e2e)', () => {
  let app: INestApplication
  let server: SERVER_TYPE

  beforeEach(async () => {
    const moduleFixture: TestingModule = await Test.createTestingModule({
      imports: [AppModule],
    }).compile()

    app = moduleFixture.createNestApplication()
    await app.init()
    // Reference the server instance
    server = app.getHttpServer()
  })

  afterEach(async () => {
    await app.close()
    // Close the server instance after each test
    server.close()
  })

  it('/ (GET)', async () => {
    // Make the request on the server instance
    return await request(server)
      .get('/')
      .expect(HttpStatus.OK)
      .expect('Hello World!')
  })

I also noticed that you're using beforeEach and afterAll. Creating a new app for each test may cause issues for the HTTP server. However, this is just my opinion.

import { Test, TestingModule } from '@nestjs/testing'
import { HttpStatus, INestApplication } from "@nestjs/common";
import * as request from 'supertest'
import { AppModule } from '../src/app.module'

beforeEach(() => {
  ...
})

afterEach(() => {
  ...
})

describe('tests', () => {
  ...
})

But ultimately, it's up to you and your preference. :)

UPDATE: Corrected the use of beforeEach instead of beforeAll since we need to close the server before EACH test, not globally.

UPDATE 2: Utilizing async/await is crucial, as the request is asynchronous and needs to be awaited for completion.

Answer №3

Starting fresh with a brand new app in the beforeEach hook and only tearing it down in the afterAll hook could lead to memory leaks as hidden references may be preventing proper garbage collection. By assigning a new instance to the app variable, previous references may not be cleared properly - such as the reference obtained by the request function.

To prevent this, switch from using beforeEach to beforeAll and you should resolve any potential memory leaks.

Answer №4

If you're still facing errors even after closing the connection and it's an intermittent issue, consider including --no-cache --watchAll in your command. Here is the complete syntax to try:

"test": "jest --watchAll --no-cache --detectOpenHandles"

Answer №5

I encountered a similar problem.

    "test:e2e": "jest --config ./test/jest-e2e.json --no-cache --detectOpenHandles",

This solution worked perfectly for me.

Answer №6

In my case, I needed to disconnect from the server and the client of my databases.

afterAll(async () => {
 await server.disconnect();
 await databaseClient.close();
});

Answer №7

Instead of using the variable it, consider replacing it with test and then passing done as a parameter to call it. I found this approach to be effective in my case.

test('mutation', async (done) => {
    const mutation = {
      query: `mutation Create($title: String!) {
        create(title: $title) {
          id,
          title
        }
      }`,
      variables: {
        title: 'Mon programme',
      },
    }
    const response = request(app.getHttpServer())
      .post('/graphql')
      .send(mutation)
     expect(response).to.be(HttpStatus.Ok)
     done()
  })

Answer №8

// for every single test

it('the provided explanation', (done) => {
        request(app)
          .get('/some-path')
          .end(done);
  });

Answer №9

Thanks Toomuchrice4u for the helpful answer. Their solution involved implementing a logout method within a service utilized by a component, which was then invoked within an afterEach block as shown below:

afterEach(async () => {

await userService.logout();

});

Answer №10

Dealt with a mongoose issue before and resolved it by implementing process.exit() in my overall cleanup file.

Answer №11

Issue: TCPWRAP

I encountered a problem where I was closing the mongo connection in the global teardown section. However, in one of my test case files, I had defined functions and functionality related to mongo but never actually used them anywhere. Once I removed those unused declarations, the issue was resolved.

Answer №12

Make sure to review your package.json file under the scripts section for the presence of the test:e2e command. If you see it, be sure to check the content and remove any instances of the parameter --detectOpenHandles. The script configuration should resemble:

"test:e2e": "jest --config ./test/jest-e2e.json --forceExit"

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

Installation and execution of TypeScript jQuery / Bootstrap definition file on a local machine using npm typings: A step-by-step guide

Struggling to set up TypeScript jQuery and Bootstrap definition files in my new project using npm typings. Below are the steps I followed: 1- Open cmd, navigate to my project folder, and enter the following commands: npm install typings --global typings ...

Accessing node_modules in TypeScript within an Asp.Net Core application

As I work on building a straightforward ASP.NET Core application utilizing npm and TypeScript, the structure of my project is organized as follows: / root | wwwroot | js | AutoGenerated // <-- TS output goes here | view | i ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

The angular framework is unable to assign a value to the property 'xxxx' because it is currently undefined

I am currently working on a simple application using Ionic (angular) and I am facing an issue with the error message: Cannot set property 'origin' of undefined Below is the interface for Product.ts: export interface Products{ id: number ...

Getting a specific array from the API with fetch in Angular: A step-by-step guide

I am trying to retrieve images from an API, but I'm having trouble accessing all the arrays to get to the data. Currently, I am only able to fetch the posts arrays in a single call and not beyond that. https://i.stack.imgur.com/aFWlD.jpg My method fo ...

Unable to create resource in nestjs due to typeScript compatibility issue

Encountered an Error: TypeError: Cannot access 'properties' property of undefined Failed to execute command: node @nestjs/schematics:resource --name=post --no-dry-run --language="ts" --sourceRoot="src" --spec Attempts made ...

The 'Subscription' type does not contain the properties: source, operator, lift, subscribe, and three other properties that are present in the 'Observable<EnumValue[]>' type

Are you struggling with assigning an Observable<EnumValue[]> to another Observable<EnumValue[]>? fetchContactLocationStates() { this.contactLocationStates$ = this.enumValues$ .pipe(takeUntil(this.destroy$)) .subscribe(x => x.fil ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

Jest has encountered an error: TypeError - It is impossible to access the properties of an undefined object (specifically attempting to read '

I have recently started working with jest testing and decided to create a straightforward test for one of my controls. This test is designed to either send an array of user objects or display the text "No users found" if the array is empty. The goal of thi ...

Angular 5 internationalization now supports the ability to access translation strings from places other than just templates

Currently, I am working with Angular 5.x and utilizing the 'i18n' directive for translation purposes. While I have had success with translating in the .html file and template, I am struggling to find a solution for doing so in the typescript file ...

Definition of type instantiation in TypeScript

When utilizing the mynew function with a specified array of classes, I am encountering an error related to defining unknown. How can I modify this definition in order to eliminate the error? export interface Type<T> extends Function { new (...arg ...

When utilizing AngularFire with Firebase Firestore Database, users may encounter instances where data duplication occurs on

Currently facing a challenge in my Angular 13.1 Project utilizing @angular/fire 7.4.1 for database management The issue arises consistently across various screens where data from Firestore Database is displayed, particularly on List screens. The lists are ...

A step-by-step guide to configuring a middleware exclusively for a particular resolver within a Graphql backend utilizing Apollo Express

If you're working with a Rest API and want to set a middleware for a specific route, you can do so using this example: router .route('/top-5-cheap') .get(tourControllers.middleAliasApi, tourControllers.getAllTours); In this scenario, th ...

Precise object mapping with Redux and Typescript

In my redux slice, I have defined a MyState interface with the following structure: interface MyState { key1: string, key2: boolean, key3: number, } There is an action named set which has this implementation: set: (state: MyState, action: PayloadAct ...

TypeScript enum type encompassing all potential values

One thing I have learned is that keyof typeof <enum> will give us a type containing all the possible keys of an enum. For example, if we have enum Season{ WINTER = 'winter', SPRING = 'spring', SUMMER = 'summer', AUT ...

Ways to address the issue arising from the utilization of the "as" keyword

Every time I encounter this issue - why must I always provide all the details? type Document = Record<string, any> type FilteredDocument<T extends Document> = {[key in keyof T as T[key] extends (()=>void) ? never : key]: T[key]} const ...

Guidelines for Managing Test Cases for a Promise-Returning Function with Resolve and Reject in Angular 6

I need to write a test case for a function that returns a Promise with resolve and reject. Here's the function definition: isAuthSuccess(): Promise<any> { const promise = new Promise((resolve, reject) => { if (this.userInfo) { ...

Is there a potential issue in Next.js 14 when utilizing the "useClient" function alongside conditional rendering in the app/layout.tsx file?

Within my app, there is a Navbar that will only be visible when the route is either "/" or "/teachers". The Navbar will not appear on the dashboard page ("/dashboard"). I achieved this using conditional rendering in the app/layout.tsx file. "use clien ...

Stop WebStorm from automatically importing code from a different Angular project within the same workspace

I currently have an angular repository that consists of two projects: a library and an Angular application. To link the library to my project, I utilized the npm link command. Within the package.json file, I specified the entry as follows: ... "my-lib ...

Error in Mongoose Schema Configuration Detected in NestJS App

I'm currently developing an e-commerce application using NestJS and MongoDB with Mongoose. I've been facing an issue while trying to implement a user's shopping cart in the application. The error message I keep encountering is as follows: ...