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?