Load a file once the Jest environment has been properly deconstructed

I am currently working on developing a straightforward API using Express, and I have encountered an issue while attempting to add tests with Jest. When running the tests, an error is displayed:

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at BufferList.Readable (node_modules/readable-stream/lib/_stream_readable.js:179:22)
      at BufferList.Duplex (node_modules/readable-stream/lib/_stream_duplex.js:67:12)
      at new BufferList (node_modules/bl/bl.js:33:16)
      at new MessageStream (node_modules/mongodb/lib/cmap/message_stream.js:35:21)
      at new Connection (node_modules/mongodb/lib/cmap/connection.js:52:28)
/home/jonathangomz/Documents/Node/Express/Devotionals/node_modules/readable-stream/lib/_stream_readable.js:111
  var isDuplex = stream instanceof Duplex;
                        ^

TypeError: Right-hand side of 'instanceof' is not callable

Concerns arise regarding the reliability of the test results right after Jest encounters this issue:

https://i.sstatic.net/87bam.png

The test script is as follows:

const app = require("../app");
const request = require("supertest");

describe("Testing root router", () => {
  test("Should test that true === true", async () => {
    jest.useFakeTimers();
    const response = await request(app).get("/");
    expect(response.status).toBe(200);
  });
});

The Jest configuration in my package.json file is set as:

"jest": {
    "testEnvironment": "node",
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ]
  }

Additional Notes:

Despite attempting to use jest.useFakeTimers(), the issue persists and it seems like I may be implementing it incorrectly. I have also tried adding it within the beforeEach method without success.

Answer №1

For me, the solution was adding the package to the transformIgnorePatterns section in the jest configuration file.

Answer №2

To enhance your testing capabilities, try incorporating jest.useFakeTimers() immediately following all imports.

Have you considered converting your test to be async?

const app = require("../app");
const request = require("supertest");

describe("Testing root router", async () => {
  test("Ensuring that true === true", async () => {
    jest.useFakeTimers();
    const response = await request(app).get("/");
    expect(response.status).toBe(200);
  });
});

Answer №3

In order to manipulate timers in your asynchronous test, make sure to include jest.useFakeTimers('modern') before the asynchronous call. Then, add jest.runAllTimers() after the asynchronous call to fast-forward the timers for accurate testing.

const app = require("../app")
const request = require("supertest")

describe("Testing root router", () => {
  test("Should test that true === true", async () => {

    //Before asynchronous call
    jest.useFakeTimers("modern")

    const response = await request(app).get("/")

    //After asynchronous call
    jest.runAllTimers()

    expect(response.status).toBe(200)
  })
})

Answer №4

For those running Jest, consider using the --testTimeout=10000 flag to extend the timeout and avoid potential issues.

Referenced from Testing NodeJs/Express API with Jest and Supertest

The --testTimeout flag allows you to adjust Jest's default timeout from 5000ms to 10000ms, which can be crucial for database refresh requirements before testing.

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

Using flags to translate text on Google should not result in being redirected to another website

I have integrated Google's language picker with country flags into my WordPress template using the code below: <!-- Add English to Chinese (Simplified) BETA --> <a target="_blank" rel="nofollow" onclick="window.open('http://www.google. ...

What could be causing the issue of being unable to connect to the NodeJS express server from any network?

Imagine having a web server running on port 3001 with the IP address 23.512.531.56 (obviously not a real one) and then switching to another network, like your neighbor's. Now, when you try entering 23.512.531.56:3001 in Chrome, why doesn't the se ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Encountering an unexpected error with the InvalidCharacterError in IE11 when using VEE Validate in conjunction with Vue.js and babel-p

Encountering an issue in IE11 where I receive an InvalidCharacterError when attempting to validate a form using vee validate in vue.js. It seems like it might be related to a polyfill error, but I'm uncertain. I have tried debugging by removing certai ...

The custom validation process encountered an error: callback is not a valid function

Encountering an issue with a custom validator in node.js while using mongoose. The goal is to verify if a query already exists in the headerLog before attempting to insert it. Take a look at the code snippet below: var mongoose = require('mongoose& ...

Creating a dynamic method to set data for a stacked bar chart in chart.js

In the following code snippet, you can see how my stacked bar chart is rendered using Angular: <canvas baseChart [datasets]="barChartData" [labels]="barChartLabels" [options]="barChartOptions" [legend]="barChartLegend" [chartType]=" ...

Combining two asynchronous requests in AJAX

In the process of customizing the form-edit-account.php template, I have added ajax requests to enhance the functionality of the account settings form. The form allows users to modify their name, surname, age, and other details. While the ajax implementati ...

How to style a div for printing using CSS

Currently, I am working on a project that has already been completed but now requires some enhancements. To give you an overview, the project includes a search functionality that displays additional details upon clicking on the displayed name in the result ...

Unable to verify credentials for accessing the MongoDB database on localhost

Recently, I embarked on a new project using Express and decided to utilize MongoDB as my database due to Node.js being the backend technology. This is my first time working with Mongo, and although I can authenticate successfully from the terminal, I' ...

Create dynamic connections between animated sprites using Three.js

I am attempting to insert lines between animated sprites, similar to the example provided. Despite trying various solutions, I have been unsuccessful in creating either a dynamic or static line between these animated sprites. Is it feasible to generate a d ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

What are the steps to integrate node-inspector with `npm start` in my application?

Currently, I am utilizing npm start to kickstart my MEAN stack application. However, I am interested in using the node-inspector to debug some Mongoose aspects. I am aware that the node inspector can be initiated with node-inspector, but I am unsure of wha ...

Retrieving Information from a PHP Backend using Ajax Requests

Just starting out with PHP and eager to learn. I've saved my php file in the www folder on my WAMP server. <?php echo 'Hi'; ?> To run it, I simply go to http://127.0.0.1/testRequestParameter.php in my browser and it displays Hi ...

Discover the position within a two-dimensional array

Suppose I have an array that contains objects, and each object has its own id property. In this case, I can find the index by writing: data.findIndex(x=>x.id === newData.id); Now, if data is an array of arrays of objects, how can I efficiently get two ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

Determine the point spread using Jquery

Trying to figure out the point spread and determine the winner of a game based on the entered scores. I've created a function to calculate the total number of points and another function to calculate the point spread and assign a winner label. However ...

javascript Incorrectly using location.reload will not refresh the page as intended

My goal is to refresh a page every time a user clicks a button so the page reverts back to its original source code. However, I am facing an issue where the location.reload() function is being executed after the code instead of at the beginning. btn.addEve ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

After upgrading from Vuetify version 1.5 to 2.0.18, an issue arises with modules not being found

I encountered the following error: module not found error To address this issue, I took the following steps: Commented out import 'vuetify/src/stylus/main.styl' in the src/plugins/vuetify.js file. Added import 'vuetify/src/styles/main. ...

Mobile site experiencing slow scrolling speed

The scrolling speed on the mobile version of my website, robertcable.me, seems to be sluggish. Despite conducting thorough research, I have not been able to find a solution. I have attempted to address the issue by removing background-size: cover from my ...