Issue with mssql.connect await causing timeout in Jest

Testing some functionality in a nextjs Typescript project that needs to interact with the database directly, not relying on mocked sql query results. But encountering issues with it actually writing to the database.

A brief example of the problem:

/* @/lib/db.ts */
import sql, { ConnectionPool } from "mssql";

const sqlConfig: sql.config = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: process.env.DB_HOST!,
  pool: {
    max: parseInt(process.env.MAX_DB_CONNECTIONS || "10"),
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: true // switch to true for local dev / self-signed certs
  }
};

if (!global.db) {
  global.db = { pool: null };
}

export async function connectToDatabase(): Promise<ConnectionPool> {
  if (!global.db.pool) {
    console.log("No pool available, creating new pool."); 
    const pool = await sql.connect(sqlConfig);
    global.db.pool = pool;
    console.log("Created new pool."); 
    
  }
  return global.db.pool!;
}
/* db.test.ts */

import { connectToDatabase } from "@/lib/db";
// Tried setting high timeout as connection shouldn't take long in development
jest.setTimeout(30000);

describe("Database", ()=>{
  it("can connect", async()=>{
    const pool = await connectToDatabase();
    expect(1).toBe(1);
  });
});

export {};

The issue lies in the connectToDatabase() Promise not fulfilling during testing (it also doesn't reject when credentials are incorrect).

Verified that environment data is correctly read by outputting sqlConfig. The functions in db.ts work fine in development.

Any insights on why this might be failing in jest?

Answer №1

Great news, I've located the solution:

Upon a thorough examination of the error log, it became apparent that I had only reviewed the lower portion (disregard the discrepancy in file names from the original inquiry):

  ControllingTableLock
    ✕ works (30016 ms)

  ● ControllingTableLock › works

    ReferenceError: setImmediate is not defined

      at node_modules/mssql/lib/base/connection-pool.js:402:9
          at Array.forEach (<anonymous>)
      at node_modules/mssql/lib/base/connection-pool.js:401:26

  ● ControllingTableLock › works

    thrown: "Exceeded timeout of 30000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

       5 |
       6 | describe("ControllingTableLock", ()=>{
    >  7 |   it("works", async()=>{
         |   ^
       8 |     const pool = await connectToDatabase();
       9 |     expect(1).toBe(1);
      10 |     return;

Further investigation revealed that

setImmediate is not defined

is an issue arising from jest using the jsdom environment instead of node.

The resolution was straightforward: I included

/*
* @jest-environment node
*/

at the top of the test file before the imports.

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

Unleashing the power of plugins and custom configurations in your next.js next.config.js

const optimizeNext = require('next-compose-plugins'); const imageOptimization = require('next-optimized-images'); const config = { target: 'serverless', }; module.exports = optimizeNext([imageOptimization], config); tra ...

Problem with Metadata Changes in Next.js: Metadata Getting Reset After Rebuilding .next Directory

I've run into a problem while trying to customize metadata in my Next.js app. Even though I can successfully make changes to the metadata in my layout.tsx file, these modifications are not showing up in the console output. Additionally, whenever I del ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. After creating the code in codesandbox and previewing the output, I noticed that the title is not aligned properly. HTML↓ < ...

Using TypeScript with React and Material-UI: Issue with undefined theme in createStyles()

Currently, I am delving into React with TypeScript and utilizing the Material UI framework for the frontend. In my quest to activate media queries, an error has crossed my path: Uncaught TypeError: Cannot read property 'up' of undefined ...

Error in Angular 2 after transition to @types: encountering "require" name not found issue

After transitioning my project from old typings to types-publisher, I have successfully resolved most of my dependencies. However, I am consistently encountering an error that reads Cannot find name 'require'. Below is a snippet from my tsconfig. ...

Transform the date format in react.js using information provided by an API endpoint

I'm currently working on a project using React and TypeScript where I need to format the date retrieved from an API. I am able to map over the data and display it, but I'm struggling to convert it into a format like '22 June 2021'. The ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

Implement the properties encapsulation design pattern

In need of a method to control document activation logic, where activating a document involves adding it to a list of activeDocuments and setting a flag to true. Direct access to the isActive property should be prohibited. class DocumentService { pr ...

The magical form component in React using TypeScript with the powerful react-final-form

My goal is to develop a 3-step form using react-final-form with TypeScript in React.js. I found inspiration from codesandbox, but I am encountering an issue with the const static Page. I am struggling to convert it to TypeScript and honestly, I don't ...

Getting the desired value from a CreatableSelect in React can be achieved by following these steps:

I have a form that includes a React library component called React Select. I'm struggling to retrieve the target value of this input field. Here's my code snippet: # CreatableSelect tag <CreatableSelect className={Astyle.selectInput} i ...

Encountering an issue with "RangeError: Invalid time value" while trying to pass a variable into the new Date() function

function fetchDate() { const router = useRouter(); const { location, startDate, endDate, numOfGuests } = router.query; const formattedStartDate = format(new Date(startDate), "dd, MMMM yyyy"); const formattedEndDate = format ...

Tips for reinitializing a redirected page from a client component in Next JS version 13 or newer

I have a client component that is being called on a page. The component contains a button that, when clicked, makes a POST request and redirects to another page. To achieve this functionality, I am using the useRouter() hook from the next/navigation. Every ...

Enhance the Nuxt 3 experience by expanding the functionality of the NuxtApp type with

When I include a plugin in my NuxtApp, it correctly identifies its type. https://i.stack.imgur.com/UFqZW.png However, when I attempt to use the plugin on a page, it only displays the type as "any." https://i.stack.imgur.com/hVSzA.png Is there a way for ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

Encountering Issue Retrieving Database URL from .env in Drizzle-Kit's drizzle.config.ts file using Next.js 14

Currently, I am using Drizzle-Kit to manage my database tables by executing drizzle-kit push:pg. However, this command requires a drizzle.config.ts file with necessary configurations like schema, output, and credentials. Normally, I store sensitive creden ...

When utilizing Angular 2, this message is triggered when a function is invoked from the Observable

One of my services is set up like this: @Injectable() export class DataService { constructor(protected url: string) { } private handleError(error: Response) { console.log(this.url); return Observable.throw(new AppError(error)); ...

Looking for help with setting up Nodemailer and installing it via NPM

I am currently developing a mobile application using Ionic with Angular/Typescript, and I'm in need of a front-end solution to dynamically send emails in the background to a specific email address. I tried using emailjs, but it requires JavaScript whi ...

Is there a way to send both a file and JSON data in a single HTTP request?

Once I developed a small application using NestJs where I implemented a BFF (Backend for Frontend) service. Within this service, I tried to execute a POST request to create a new user while also including the user's avatar in the same request. Here is ...

The useEffect hook is failing to resolve a promise

I have received a response from an API that I need to display. Here is a snippet of the sample response (relevant fields only): [ { ...other fields, "latitude": "33.5682166", "longitude": "73 ...

When working with Expo and React Native in TypeScript, VS code IntelliSense recommends using 'react-native/types' instead of just 'react-native'

My React Native TypeScript setup is showing react-native/types instead of react-native in IntelliSense. How can I fix this issue? I initialized my project using npx create-expo-app MyApp --template Typescript. Here is my tsconfig.json configuration. { ...