I am having a function, where I am doing some db operations. Like,
const { Pool } = require("pg");
const pool = new Pool({
connectionString: `some connection string...`,
});
var fun = async function (pk_name, pk_value) {
try {
const db = await pool.connect();
const query = `SELECT *
FROM creds
WHERE ${pk_name} = $1`;
var res = await db.query(query, [pk_value]);
db.release();
return res.rows;
} catch (ex) {
return [];
}
};
module.exports.isValidUser = async function (pk_name, pk_value, password) {
try {
var userData = await fun(pk_name, pk_value);
return userData[0].email === pk_value && userData[0].password === password;
} catch (ex) {
return false;
}
};
and I am trying to mock the above methods like pool.connect()
,db.query()
and db.release()
so, I tried following things
var sinon = require("sinon");
var assert = sinon.assert;
const { Pool } = require("pg");
const pool = new Pool()
var databaseControllerTestPositive = function () {
it("valid user check test", async function () {
sinon.stub(logUtils, "info");
sinon.stub(pool, 'connect')
sinon.stub(pool, 'query').returns({
email: "demo@gmail.com",
password: "demo"
})
sinon.stub(pool.prototype.connect, "release");
// isValidUser is another function which calls the above fun() internally.
var result = await dbUtils.isValidUser(
"fake_pk_name",
"fake_pk_value",
"pass"
);
assert.match(result, { rows: [] });
});
};
But, the above test is failing and the methods which I was trying to mock, is not really getting mocked.
I have found a similar question, but I didn't find it's answer so helpful.
Could anyone please help me, if I am doing anything wrong.