In a previous project I mocked the mysql library with Sinon. I did this like so:
X.js
:
const con = mysql.createPool(config.mysql);
...
Some other place in the project
:
const rows = await con.query(query, inserts);
...
X.test.js
:
const sinon = require('sinon');
const mockMysql = sinon.mock(require('mysql'));
...
mockMysql.expects('createPool').returns({
query: () => {
// Handles the query...
},
...
It worked perfectly.
In another project I am trying to mock pg, again with Sinon.
pool.js
:
const { Pool } = require('pg');
const config = require('@blabla/config');
const pool = new Pool(config.get('database'));
module.exports = pool;
Some other place in the project
:
const con = await pool.connect();
const result = await con.query(...
Y.test.js
:
???
I can't understand how to mock connect().query()
. None of the following approaches work:
1:
const { Pool } = require('pg');
const config = require('@blabla/config');
const mockPool = sinon.mock(new Pool(config.get('database')));
...
mockPool.expects('connect').returns({
query: () => {
console.log('query here');
},
});
1 results in no error but the real db connection is used.
2:
const { Pool } = sinon.mock(require('pg'));
const config = require('@blabla/config');
const pool = new Pool(config.get('database'));
pool.expects('connect').returns({
query: () => {
console.log('query here');
},
});
2 => TypeError: Pool is not a constructor
3:
const { Pool } = sinon.mock(require('pg'));
const config = require('@blabla/config');
const pool = sinon.createStubInstance(Pool);
pool.connect.returns({
query: () => {
console.log('query here');
},
});
3 => TypeError: The constructor should be a function.
Can anybody point me in the right direction with how to mock my PostgreSQL connection?