Currently, I have setup my code as follows:
import pgPromise from "pg-promise";
const pgp = pgPromise();
export const createDBConnection = async () => {
const db = pgp({
host: "",
ssl: false,
user: "",
password: "",
port: 3306,
max: 25
});
try {
const connection = await db.connect();
connection.done();
} catch (err) {
console.error(err)
}
return db;
}
and my test as follows:
import { createDBConnection } from ".";
jest.mock('pg-promise');
describe('db', () => {
it('initialises with correct parameters', async () => {
await createDBConnection();
...
});
});
Unfortunately, the test fails with:
TypeError: pgp is not a functio
n
The following works:
import { createDBConnection } from ".";
jest.mock('pg-promise', () => () => jest.fn());
describe('db', () => {
it('initialises with correct parameters', async () => {
await createDBConnection();
});
});
and
const pgpMock = jest.fn().mockImplementation(() => ({
connection: jest.fn().mockReturnValue({ end: jest.fn() }),
connect: jest.fn().mockReturnValue({ done: jest.fn() })
}));
jest.mock('pg-promise', () => () => pgpMock);
import { createDBConnection } from '.';
describe('db', () => {
it('initialises with correct parameters v1', async() => {
await createDBConnection();
expect(pgpMock).toHaveBeenCalled();
});
});
But I am looking to use jest.mocked so I can check that pgp function is called with the correct parameters since these might come from an external configuration.
import pgPromise from 'pg-promise';
import { createDBConnection } from '.';
jest.mock('pg-promise');
describe('db', () => {
it('initialises with correct parameters v1', async() => {
const pgpMock = jest.fn().mockImplementation(() => ({
connection: jest.fn().mockReturnValue({ end: jest.fn() }),
connect: jest.fn().mockReturnValue({ done: jest.fn() })
}));
jest.mocked(pgPromise).mockReturnValue(() => pgpMock);
await createDBConnection();
expect(pgpMock).toHaveBeenCalled();
});
});
Which makes pgp to be undefined when called.
I am using the following libraries:
"pg-promise": "^11.9.0"
"jest": "^29.7.0",
"ts-jest": "^29.2.0",
"typescript": "^5.5.3"
I expected to be able to mock pgPromise implementation to return a mock function so when calling pgp({}) I can assert its parameters.
renkinjutsushi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.