I am using pg-promose inside its own module to initialise a connection to DB and then use that connection in my route modules or anywhere else its imported.
import pgPromise from 'pg-promise'
let psqlClient
const pgp = pgPromise({/* Initialization Options */ })
const connection = {
connectionString: process.env.PSQL_URI || "postgres://postgres@postgresql:5432",
max: process.env.PSQL_POOL_SIZE || 15
}
export const connectPSQL = async () => {
try {
psqlClient = pgp(connection);
} catch (e) {
console.error(`Error Connecting to DB: ${e}`);
}
}
export const getPSQLClient = () => {
return psqlClient;
};
export const getURL = () => {
return process.env.PSQL_URI
}
This is a pretty simple module however I cannot seem to wrap my head around on how to mock it in a unit test for a specific route. Following guides like this one I am doing something simple like:
import request from 'supertest';
import express from 'express';
import { getPSQLClient } from "../clients/postgresql.js";
import {get as GETFoo} from '../routes/v1/foo/index.js';
import { jest } from '@jest/globals';
jest.mock("../clients/postgresql.js")
const app = express();
app.use(express.json());
app.use('/v1/foo/index.js', GETFoo);
describe('Sample Test', () => {
it('should test that true === true', () => {
expect(getPSQLClient).toHaveBeenCalledTimes(1);
})
})
But this is returning: Matcher error: received value must be a mock or spy function
which seems like the mocking is not being done correctly.
What I ultimately want is to be able to mock query results since my route involves querying like:
let result = await psqlClient.any(
"SELECT * FROM goo WHERE id=$1 LIMIT 1",
[req.params.rid]
)
I just want to plug in my own mocked result