fake pool connection using sinon js - node.js

I just want to fake pool connection and
use the connection in all my unit test.
const logger = require('./logger.js');
const { Pool } = require ('pg');
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var assert = sinon.assert;
const pool = new Pool ({
connectionString: process.env.HEROKU_POSTGRESQL_BLUE_URL,
ssl: {
rejectUnauthorized: false
},
//max: 500
});
async function queryWithParameter(queryToExecute,parameterReq) {
var result;
var finalResult;
try{
const client = await pool.connect();
try{
if(parameterReq == null)
result = await client.query(queryToExecute);
else
result = await client.query(queryToExecute, parameterReq);
finalResult = result.rows;
}
catch(err){
logger.error('error in queryWithParameter : ' + err);
}
finally{
client.release(true);
}
}
catch (err){
}
return finalResult;
}
module.exports = {
queryWithParameter
};
I'm supposed to use sinon.js to fake the pool connection so I cannot hit the actual DB but failed to implement it successfully.

I will show you how to test the test cases that "should be the correct query result".
index.js:
const { Pool } = require('pg');
const pool = new Pool({
connectionString: process.env.HEROKU_POSTGRESQL_BLUE_URL,
ssl: {
rejectUnauthorized: false,
},
});
async function queryWithParameter(queryToExecute, parameterReq) {
var result;
var finalResult;
try {
const client = await pool.connect();
try {
if (parameterReq == null) result = await client.query(queryToExecute);
else result = await client.query(queryToExecute, parameterReq);
finalResult = result.rows;
} catch (err) {
console.error('error in queryWithParameter : ' + err);
} finally {
client.release(true);
}
} catch (err) {}
return finalResult;
}
module.exports = { queryWithParameter };
index.test.js:
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('69222273', () => {
it('should query result', async () => {
process.env.HEROKU_POSTGRESQL_BLUE_URL = 'whatever';
const res = { rows: [{ message: 'Hello world!' }] };
const clientStub = { query: sinon.stub().resolves(res), release: sinon.stub() };
const poolStub = { connect: sinon.stub().resolves(clientStub) };
const pgStub = { Pool: sinon.stub().returns(poolStub) };
const { queryWithParameter } = proxyquire('./', {
pg: pgStub,
});
const actual = await queryWithParameter('SELECT $1::text as message', ['Hello world!']);
sinon.assert.calledWithExactly(pgStub.Pool, {
connectionString: 'whatever',
ssl: {
rejectUnauthorized: false,
},
});
sinon.assert.calledOnce(poolStub.connect);
sinon.assert.calledWithExactly(clientStub.query, 'SELECT $1::text as message', ['Hello world!']);
sinon.assert.match(actual, [{ message: 'Hello world!' }]);
sinon.assert.calledWithExactly(clientStub.release, true);
});
});
test result:
69222273
✓ should query result (1350ms)
1 passing (1s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 84.62 | 50 | 100 | 91.67 |
index.js | 84.62 | 50 | 100 | 91.67 | 22
----------|---------|----------|---------|---------|-------------------

Related

TypeError: AWS.SecretsManager is not a constructor in unit testing with proxyquire

I have written a test code to test code that gives credentials from AWS Secret Manager. I used proxyquire and sinon for stubbing and getting this error.
Function I want to test
exports.getCredsFromAWSSecretsManager = (keyName) => {
const SM = new AWS.SecretsManager({
apiVersion: process.env.AWS_SM_API_VERSION,
region: process.env.AWS_SM_REGION
});
return SM.getSecretValue(params).promise().then((data) => {
logger.info(logMsgs.awsHlpr_smGetSecretValueSuccess(JSON.stringify(data)));
return JSON.parse(data.SecretString);
}).catch((err) => {
logger.error(logMsgs.awsHlpr_smGetSecretValueErr(JSON.stringify(err)));
throw err;
});
};
Test case that I have written
const sinon = require("sinon");
const proxyquire = require("proxyquire").noCallThru().noPreserveCache();
const { mockLogger } = require("../../mockdata/mockLogger");
let awsHelper;
let secretsManagerStub;
describe.only("AWS Helper ", () => {
// function1
describe("AWS Helper: getCredsFromAWSSecretsManagera method", () => {
before((done) => {
const data = {
SecretString: JSON.stringify({ publicKey: 'secretUsername', privateKey: 'secretPassword' }),
};
secretsManagerStub = {
getSecretValue: sinon.stub().callsFake((params, callback) => {
callback(null, data);
}),
};
const awsStub = {
SecretsManager: sinon.stub().returns(secretsManagerStub)
}
awsHelper = proxyquire('../../../utils/aws_helper.js', {
'aws-sdk':{
AWS:awsStub
} ,
"../../utils/logger": mockLogger,
});
done();
});
afterEach(() => {
sinon.restore();
});
it('should write random data!', async () => {
const expectedData = "abcdef";
secretsManagerStub.getSecretValue.yields(null, expectedData);
const data = await awsHelper.getCredsFromAWSSecretsManager();
sinon.assert.callCount(secretsManagerStub.getSecretValue, 1);
assert.strictEqual(data, expectedData);
});
});
});
This code gives me the error saying
TypeError: AWS.SecretsManager is not a constructor
any help would be greatly appreciated.
AWS is a namespace, it contains all AWS service classes like SecretsManager. You should provide the awsStub to aws-sdk, there is no need to wrap the awsStub inside an object.
aws_helper.js:
const AWS = require('aws-sdk');
exports.getCredsFromAWSSecretsManager = () => {
const SM = new AWS.SecretsManager({
apiVersion: process.env.AWS_SM_API_VERSION,
region: process.env.AWS_SM_REGION,
});
const params = {
SecretId: '1',
};
return SM.getSecretValue(params)
.promise()
.then((data) => {
console.info(data);
return JSON.parse(data.SecretString);
})
.catch((err) => {
console.error(err);
throw err;
});
};
aws_helper.test.js:
const sinon = require('sinon');
const proxyquire = require('proxyquire').noCallThru().noPreserveCache();
let awsHelper;
let secretsManagerStub;
describe('AWS Helper: getCredsFromAWSSecretsManagera method', () => {
before(() => {
const data = {
SecretString: JSON.stringify({ publicKey: 'secretUsername', privateKey: 'secretPassword' }),
};
secretsManagerStub = {
getSecretValue: sinon.stub().returnsThis(),
promise: sinon.stub().resolves(data),
};
const awsStub = {
SecretsManager: sinon.stub().returns(secretsManagerStub),
};
awsHelper = proxyquire('./aws_helper.js', {
'aws-sdk': awsStub,
});
});
afterEach(() => {
sinon.restore();
});
it('should write random data!', async () => {
const data = await awsHelper.getCredsFromAWSSecretsManager();
sinon.assert.callCount(secretsManagerStub.getSecretValue, 1);
sinon.assert.match(data, { publicKey: 'secretUsername', privateKey: 'secretPassword' });
});
});
test result:
AWS Helper: getCredsFromAWSSecretsManagera method
{
SecretString: '{"publicKey":"secretUsername","privateKey":"secretPassword"}'
}
✓ should write random data!
1 passing (2s)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 77.78 | 100 | 66.67 | 77.78 |
aws_helper.js | 77.78 | 100 | 66.67 | 77.78 | 19-20
---------------|---------|----------|---------|---------|-------------------

How to mock the connect, query, and release methods of pool in postgreSql using sinon?

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.
You can use Link Seams, so we need a extra package - proxyquire. Since the fun function is not exported, we can't require it and test it directly. We need to test it together with isValidUser function.
E.g.
main.js:
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;
}
};
main.test.js:
const proxyquire = require('proxyquire');
const sinon = require('sinon');
var assert = sinon.assert;
describe('65940805', () => {
it('valid user check test', async function () {
const res = { rows: [{ email: 'fake_pk_value', password: 'pass' }] };
const dbStub = {
query: sinon.stub().resolves(res),
release: sinon.stub(),
};
const poolInstanceStub = {
connect: sinon.stub().resolves(dbStub),
};
const PoolStub = sinon.stub().returns(poolInstanceStub);
const dbUtils = proxyquire('./main', {
pg: {
Pool: PoolStub,
},
});
var result = await dbUtils.isValidUser('fake_pk_name', 'fake_pk_value', 'pass');
assert.match(result, true);
sinon.assert.calledWithExactly(PoolStub, {
connectionString: `some connection string...`,
});
sinon.assert.calledOnce(poolInstanceStub.connect);
sinon.assert.calledWithExactly(dbStub.query, sinon.match.string, ['fake_pk_value']);
sinon.assert.calledOnce(dbStub.release);
});
});
unit test result:
65940805
√ valid user check test (1013ms)
1 passing (1s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 86.67 | 100 | 100 | 86.67 |
main.js | 86.67 | 100 | 100 | 86.67 | 17,26
----------|---------|----------|---------|---------|-------------------

Writing unit test for the azure redis cache in nodejs

I am trying to write a unit test case using mocha framework, where I have to mock an azure redis cache...Can someone help me on how to mock cache for unit test case purpose using node.js.
const redis = require('redis');
const redisHostName = process.env['hostName'];
const redisPort = process.env['port'];
const redisKey = process.env['key'];
let client = redis.createClient(redisPort, redisHostName, { auth_pass: redisKey, tls: { serverName: redisHostName } });
async function getKeyValue(key, ctx) {
context = ctx;
return new Promise((resolve, reject) => {
client.get(key, function (err, result) {
if (err) {
resolve(err);
}
resolve(result);
});
});
}
getKeyValue();
Here is the unit test solution:
index.js
const redis = require('redis');
const redisHostName = process.env['hostName'];
const redisPort = process.env['port'];
const redisKey = process.env['key'];
let client = redis.createClient(redisPort, redisHostName, { auth_pass: redisKey, tls: { serverName: redisHostName } });
async function getKeyValue(key, ctx) {
context = ctx;
return new Promise((resolve, reject) => {
client.get(key, function(err, result) {
if (err) {
return resolve(err);
}
resolve(result);
});
});
}
exports.getKeyValue = getKeyValue;
index.test.js:
const sinon = require('sinon');
const redis = require('redis');
describe('60870408', () => {
beforeEach(() => {
process.env['hostName'] = '127.0.0.1';
process.env['port'] = 6379;
process.env['key'] = 'test';
});
afterEach(() => {
delete require.cache[require.resolve('./')];
sinon.restore();
});
it('should get value', async () => {
const client = {
get: sinon.stub().callsFake((key, callback) => callback(null, 'elsa')),
};
const createClientStub = sinon.stub(redis, 'createClient').returns(client);
const { getKeyValue } = require('./');
sinon.assert.calledWithExactly(createClientStub, '6379', '127.0.0.1', {
auth_pass: 'test',
tls: { serverName: '127.0.0.1' },
});
const actual = await getKeyValue('name', {});
sinon.assert.match(actual, 'elsa');
sinon.assert.calledWithExactly(client.get, 'name', sinon.match.func);
});
it('should handle error', async () => {
const mError = new Error('network');
const client = {
get: sinon.stub().callsFake((key, callback) => callback(mError)),
};
const createClientStub = sinon.stub(redis, 'createClient').returns(client);
const { getKeyValue } = require('./');
sinon.assert.calledWithExactly(createClientStub, '6379', '127.0.0.1', {
auth_pass: 'test',
tls: { serverName: '127.0.0.1' },
});
const actual = await getKeyValue('name', {});
sinon.assert.match(actual, mError);
sinon.assert.calledWithExactly(client.get, 'name', sinon.match.func);
});
});
unit test results with 100% coverage:
60870408
✓ should get value
✓ should handle error
2 passing (28ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------

Sinon Calling a function passed as an argument to a constructor

I have the following classes A and B,
class A {
listenResponse(port, callback) {
const server = new CustomServer(port, (error, response) => {
if (error) return callback(error);
callback(null, response);
});
}
}
class CustomServer {
constructor(port, callback) {
this.port = port;
this.server = http.createServer((request, response) => {
if(// condition) { return callback(error); }
callback(null, response);
});
}
}
How do I test the function passed to CustomServer constructor while unit testing class A? Any help is highly appreciated.
Here is the unit test solution using an additional module proxyquire:
a.js:
const CustomServer = require('./customServer');
class A {
listenResponse(port, callback) {
const server = new CustomServer(port, (error, response) => {
if (error) return callback(error);
callback(null, response);
});
}
}
module.exports = A;
customServer.js:
class CustomServer {
constructor(port, callback) {
this.port = port;
this.server = http.createServer((request, response) => {
callback(null, response);
});
}
}
module.exports = CustomServer;
a.test.js:
const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('60084056', () => {
it('should get response', () => {
const error = null;
const response = {};
const customServerStub = sinon.stub().yields(error, response);
const A = proxyquire('./a.js', {
'./customServer': customServerStub,
});
const a = new A();
const port = 3000;
const callback = sinon.stub();
a.listenResponse(port, callback);
sinon.assert.calledWithExactly(customServerStub, port, sinon.match.func);
sinon.assert.calledWithExactly(callback, null, response);
});
it('should handle error', () => {
const error = new Error('network');
const response = {};
const customServerStub = sinon.stub().yields(error, response);
const A = proxyquire('./a.js', {
'./customServer': customServerStub,
});
const a = new A();
const port = 3000;
const callback = sinon.stub();
a.listenResponse(port, callback);
sinon.assert.calledWithExactly(customServerStub, port, sinon.match.func);
sinon.assert.calledWithExactly(callback, error);
});
});
Unit test results with coverage report:
60084056
✓ should get response (1684ms)
✓ should handle error
2 passing (2s)
-----------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------------|---------|----------|---------|---------|-------------------
All files | 70 | 100 | 50 | 66.67 |
a.js | 100 | 100 | 100 | 100 |
customServer.js | 25 | 100 | 0 | 25 | 3-5
-----------------|---------|----------|---------|---------|-------------------
Source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/60084056

nodejs - sinon stub not being called

For some reason I am having a little trouble getting this simple test to run correctly with a similar set-up I have used multiple times before.
Perhaps a fresh pair of eyes could help me understand why my method generateReport is not being invoked and none of my stubs are being triggered with the intended arguments?
BYE nor GOOD are ever logged and the tests are returning the error: AssertError: expected stub to be called with arguments
My index file:
const errorHandler = require('./lib/handlers/error-handler')
const transformRequest = require('./lib/handlers/request-converter')
const convert = require('./lib/convert')
exports.generateReport = function generateReport(req, res) {
console.log('HELLO')
const objectToPopulateTemplate = transformRequest(req.body)
convert(objectToPopulateTemplate, function (e, data) {
if (e) {
console.log('BYE')
const error = errorHandler(e)
return res.send(error.httpCode).json(error)
}
console.log('GOOD')
res
.set('Content-Type', 'application/pdf')
.set('Content-Disposition', `attachment; filename=velocity_report_${new Date()}.pdf`)
.set('Content-Length', data.length)
.status(200)
.end(data)
})
}
My test file:
const proxyquire = require('proxyquire')
const assert = require('assert')
const sinon = require('sinon')
const fakeData = require('./data/sample-request.json')
describe('report-exporter', () => {
describe('generateReport', () => {
const fakeError = new Error('Undefined is not a function')
let res, resSendStub, resStatusStub, resEndStub, resSetStub, resJsonStub, req, convertStub, generate
before(() => {
resSendStub = sinon.stub()
resJsonStub = sinon.stub()
resStatusStub = sinon.stub()
resEndStub = sinon.stub()
resSetStub = sinon.stub()
convertStub = sinon.stub()
res = {
send: function(errorCode) {
return resSendStub(errorCode)
},
json: function(object) {
return resJsonStub(object)
},
set: function(arg1, arg2) {
return resSetStub(arg1, arg2)
},
status: function(code) {
return resStatusStub(code)
},
end: function(data) {
return resEndStub(data)
}
}
req = {
body: {}
}
generate = proxyquire('./../index', {
'./lib/convert': function() {
return convertStub
}
})
})
it('Should return an error response', () => {
convertStub.throws(fakeError)
generate.generateReport(req, res)
sinon.assert.calledWith(resSendStub, '500')
})
})
})
It looks like you are proxyquireing your ./lib/convert incorrectly. Original convert is called with objectToPopulateTemplate and a callback function (e, data). And that's the callback who is responsible for error handling and sending a response.
The stubbed convert function though doesn't care about about the provided callback at all, so the callback never gets called.
Most likely what you want is to pass the parameters to convertStub and deal with them later:
'./lib/convert': function(objectToPopulateTemplate, cb) {
return convertStub(objectToPopulateTemplate, cb);
}
and then
it('Should return an error response', () => {
generate.generateReport(req, res);
const cb = convertStub.getCall(0).args[1];
// simulate `convert` to fail
cb(fakeError);
sinon.assert.calledWith(resSendStub, '500')
})
Here is the unit test solution:
index.js:
const errorHandler = require("./error-handler");
const transformRequest = require("./request-converter");
const convert = require("./convert");
exports.generateReport = function generateReport(req, res) {
console.log("HELLO");
const objectToPopulateTemplate = transformRequest(req.body);
convert(objectToPopulateTemplate, function(e, data) {
if (e) {
console.log("BYE");
const error = errorHandler(e);
return res.send(error.httpCode).json(error);
}
console.log("GOOD");
res
.set("Content-Type", "application/pdf")
.set(
"Content-Disposition",
`attachment; filename=velocity_report_${new Date()}.pdf`
)
.set("Content-Length", data.length)
.status(200)
.end(data);
});
};
error-handler.js:
module.exports = function(error) {
return error;
};
request-converter.js:
module.exports = function transformRequest(body) {
return body;
};
convert.js:
module.exports = function convert(body, callback) {
callback();
};
index.spec.js:
const sinon = require("sinon");
const proxyquire = require("proxyquire");
describe("report-exporter", () => {
describe("generateReport", () => {
afterEach(() => {
sinon.restore();
});
const fakeError = new Error("Undefined is not a function");
fakeError.httpCode = 500;
it("Should return an error response", () => {
const logSpy = sinon.spy(console, "log");
const mReq = { body: {} };
const mRes = { send: sinon.stub().returnsThis(), json: sinon.stub() };
const convertStub = sinon.stub();
const errorHandlerStub = sinon.stub().returns(fakeError);
const transformRequestStub = sinon.stub().returns(mReq.body);
const generate = proxyquire("./", {
"./convert": convertStub,
"./error-handler": errorHandlerStub,
"./request-converter": transformRequestStub
});
generate.generateReport(mReq, mRes);
convertStub.yield(fakeError, null);
sinon.assert.calledWith(transformRequestStub);
sinon.assert.calledWith(convertStub, {}, sinon.match.func);
sinon.assert.calledWith(errorHandlerStub, fakeError);
sinon.assert.calledWith(logSpy.firstCall, "HELLO");
sinon.assert.calledWith(logSpy.secondCall, "BYE");
});
});
});
Unit test result with coverage report:
report-exporter
generateReport
HELLO
BYE
✓ Should return an error response (94ms)
1 passing (98ms)
----------------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------------------|----------|----------|----------|----------|-------------------|
All files | 87.5 | 50 | 62.5 | 87.5 | |
convert.js | 50 | 100 | 0 | 50 | 2 |
error-handler.js | 50 | 100 | 0 | 50 | 2 |
index.js | 84.62 | 50 | 100 | 84.62 | 14,15 |
index.spec.js | 100 | 100 | 100 | 100 | |
request-converter.js | 50 | 100 | 0 | 50 | 2 |
----------------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/47352972

Resources