I am trying to mock a database call and it keeps causing the db function to return undefined.
Please take a look at my files.
db.ts
import * as mysql from "mysql";
import * as util from "util";
{... other functions with named exports}
const getDbConnection = () => {
const pool = mysql.createPool(DB_CONFIG);
return {
query(sql: string) {
return util.promisify(pool.query).call(pool, sql);
},
};
};
export default getDbConnection;
testname.spec.ts
import { mocked } from "ts-jest/utils";
import db from "../src/utils/db";
jest.mock("../src/utils/db");
describe("Test Controller", () => {
afterAll(() => {
jest.resetAllMocks();
});
mocked(db);
it("should retrieve all", async () => {
await request(app)
.get("/data")
.expect(200)
.expect(function (res) {
expect(res.body.data).toContain("data");
});
});
});
controller.ts
import getDbConnection from "../utils/db";
const db = getDbConnection();
router.get("/", async (_, res) => {
let sql = "...";
try {
let result = await db.query(sql);
res.status(200).json(result);
} catch (error) {
console.log("DB error", error);
}
});
I am also using explicit imports for jest
import { expect, describe, it, jest, afterAll } from "@jest/globals";