What could be the reason for Jest running my TypeScript test twice and consistently failing one of the runs?

Currently, I am in the process of writing a test for a simple route within my API backend. This test is being written using Typescript and Jest, all within a docker container that I initiate using docker-compose.

For my testing purposes, I have created a helper class which initializes an express webserver and establishes a connection to the database through the init function. In the shutdown function, it handles closing the connection as needed. My test script looks like this:

import { Helper } from "./helper";
import request from 'supertest'

describe('article', () => {
    const helper = new Helper();
    beforeAll(async () => {
        await helper.init();
    });

    afterAll(async () => {
        await helper.shutdown();
    });

    it('should test if reaching the api is possible', async (done) => {
        request(helper.app)
        .get('/test')
        .send()
        .set('Accept', 'application/json')
        .expect(200)
        .end( (error, response) => {
            if(error) throw error;
            expect(response.body.message).toBe("Hello");
        });
    });

To run the test, I use the following command:

"test": "jest --verbose --forceExit --runInBand --detectOpenHandles"

After executing the test, I observed the following output:

https://i.sstatic.net/eAkPt.png

Despite adjusting the Timeout settings as recommended, there was no change in behavior. To further investigate, I temporarily modified the route to return "Helloo" instead of the expected "Hello". The result was as follows:

https://i.sstatic.net/4KvMs.png

Evidently, the response is received. However, my concern lies with why the test appears to be running twice and consistently experiencing timeouts during the second test iteration.

Here is my jest.config.js:

module.exports = {
    "roots": [
      "<rootDir>/src"
    ],
    "transform": {
      "^.+\\.tsx?$": "ts-jest"
    },
    "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
    "moduleFileExtensions": [
      "ts",
      "js"
    ],
  }

Answer №1

Solution

After gaining recent attention, I have decided to separate the solution from the original question and provide it here in this answer. I am not completely certain if this was the most effective approach, particularly since I revisited the use of jest for the second time without any prior experience with it. Nevertheless, when I initially posted the question, following these steps resolved the issue:

To successfully execute the expectations, I found it necessary to wrap them within a try-catch block, avoid labeling the test as async, but instead pass the done function and call it both after the expectations and within the catch block.

Answer №2

For asynchronous tests, it is important to make use of the done callback within your async handler's body.

An example implementation could look like this:

it('ensures that accessing the API is successful', (done) => { // << This is where the done callback is specified for async testing
        request(helper.app)
        .get('/test')
        .send()
        .set('Accept', 'application/json')
        .expect(200)
        .end( (error, response) => {
            if(error) {
              done(error);
            } else {
              expect(response.body.message).toBe("Hello");
              done();
            }
        });
    });

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

The data structure does not match the exact object type

Why isn't this code snippet functioning as expected? It seems that 'beta' has keys of type string and their values are compatible (id is a number type, and temp is also a number type). Additionally, the Record function should make the values ...

How can I resolve the issue of a React hook being called within a callback function when working with TypeScript and React?

I am trying to display the names of company and owner when sharing an item, but I am encountering an error that says "React hook cannot be used in callback function. React hooks must be called in a react functional component or a custom react hook function ...

Swapping out a class or method throughout an entire TypeScript project

Currently, I am working on a software project built with TypeScript. This project relies on several third-party libraries that are imported through the package.json file. One such library includes a utility class, utilized by other classes within the same ...

Implementing a custom overwrite function in TypeScript's inheritance

Below is a class that I have: export class RestService { private baseUrl: string; constructor(protected http: HttpClient) { this.baseUrl = environment.LOCAL_URL; } public get<T>(resource: string, params?: HttpParams): Observable< ...

The Angular Table Order Pipe does not properly reinitialize its original state

This is my first time posting a question here. The issue I'm facing involves creating a pipe to reorder a specific column in my application (in alphabetical order). The column can have 3 statuses: -1, 0, and 1, with 0 being the default initial status ...

Experimenting with asynchronous functions in React using Jest

As a newcomer to unit testing, I am working with two files: RestaurantReducer import * as Const from '../constants/Const' const RestaurantReducer = (state = { restaurantList: [] }, action) => { switch (action.type) { case Co ...

Add TypeScript typings for npm utility manually by incorporating type definitions

I'm in the process of incorporating TypeScript into an existing JavaScript project, and I'm currently facing the challenge of adding typings to an npm module that lacks type definitions, which I anticipate will be a common issue. When I try to i ...

Rendering a React/Material UI class based on the state variable in a conditional manner

I am currently working on building a basic navbar setup using React and Material UI. I have encountered an issue where React-Router-Dom does not seem to be functioning within this particular project, and implementing it would be excessive for the simple ta ...

Updating the Nuxt3 editing page with useFetch and $fetch for fetching data, along with a typed storage object that prevents loading issues

My journey with nuxt3 is still new. I am currently working on developing a new API-based app with nuxt3. Previous versions seemed to work "somehow," but they did not meet my expectations. Here are the things I am looking to cover, both in theory and in cod ...

Is it possible to retrieve the contents of a test file using Jest?

As I continue to write tests for my library, I've noticed that they are turning into a comprehensive documentation guide on how to use the library effectively. I'm curious if Jest offers an API that would enable me to extract the test content in ...

Incorporate my personalized icons into the button design of ionic 2 actionSheet

I'm struggling to figure out how to incorporate my personal icon into the actionSheet feature of ionic 2/3. presentActionSheet() { let actionSheet = this.actionSheetCtrl.create({ title: 'Mode', buttons: [ { ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

Leverage the power of react-redux useSelector with the precision of TypeScript

When attempting to utilize the new useSelector hook (shown in the example below) from react-redux in TypeScript, an error is encountered indicating that the function does not exist: Module '"../../../node_modules/@types/react-redux"' has no expo ...

What is the best way to retrieve a nested data type?

I am working with an interface named IFoo interface IFoo { name: string; version: number; init: (arg1: string, arg2: number) => Promise<string[]>; } I am interested in the type of init. Is there a way to extract it so that I can use this i ...

Ways to dynamically display components in React Native

In my React Native app, I have a custom tab control that is rendered dynamically using the following configuration: const TABS = [ { title: 'Tab 1', component: MyComponentOne }, { title: 'Tab 2', component: MyComponentTwo } ]; T ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Using a modal in a stack navigator with React Native in Expo

I'm facing an issue with stacknavigator in an expo app while trying to open a modal from it. When the modal is placed on the body of the app, everything works perfectly with no issues. However, if the modal is launched from a stack screen, most of th ...

What is the reason for the state being read-only in the Parent class when I extend a Child class from the Parent in React with Typescript

After creating an interface for the parent class defined as a State: interface ParentState { name: string; } I proceeded to create a component with the state of the aforementioned type: class Test extends React.Component<{}, ParentState> { const ...

What is the method for activating a hook after a state change in a functional component?

I'm currently working on a custom pagination hook that interacts with an API to fetch data similar to React Query. The concept is straightforward. I aim to invoke this hook whenever a specific state (referred to as cursor) undergoes a change. Below i ...

Ionic 3 and Angular 6: Json Input Ended Abruptly

I've come across numerous discussions about the error I'm experiencing, but none of the solutions seem to apply to my situation. This morning, when I ran my code, I encountered the "Unexpected end of Json Input" error. Interestingly, I hadn' ...