I just started using sinon, and I had some initial success stubbing out DynamoDB calls:
sandbox = sinon.createSandbox()
update_stub = sandbox.stub(AWS.DynamoDB.DocumentClient.prototype, 'update').returns({
promise: () => Promise.resolve(update_meeting_result)
})
This works great.
But I also need to stub Lambda, and the same approach isn't working:
lambda_stub = sandbox.stub(AWS.Lambda.prototype, 'invoke').returns({
promise: () => Promise.resolve({lambda_invoke_result}) //
})
With this, I get the error: Cannot stub non-existent property invoke.
example implementation:
const AWS = require("aws-sdk")
AWS.config.update({region: 'us-west-2'})
const dynamodb = new AWS.DynamoDB.DocumentClient()
const lambda = new AWS.Lambda()
// lambda function handler
exports.handler = async (event) => {
let result = await dynamodb.get({/* some get config */}).promise()
// do stuff ...
// kick off next lambda
await lambda.invoke({/* lambda config */}).promise()
return {"status": "ok"} // or something
}
Here is the unit test solution:
index.js:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-west-2' });
const dynamodb = new AWS.DynamoDB.DocumentClient();
const lambda = new AWS.Lambda();
exports.handler = async (event) => {
let result = await dynamodb.get({}).promise();
await lambda.invoke({}).promise();
return { status: 'ok' };
};
index.test.js:
const sinon = require('sinon');
const AWS = require('aws-sdk');
describe('61516053', () => {
afterEach(() => {
sinon.restore();
});
it('should pass', async () => {
const mLambda = { invoke: sinon.stub().returnsThis(), promise: sinon.stub() };
sinon.stub(AWS, 'Lambda').callsFake(() => mLambda);
const mDocumentClient = { get: sinon.stub().returnsThis(), promise: sinon.stub() };
sinon.stub(AWS.DynamoDB, 'DocumentClient').callsFake(() => mDocumentClient);
sinon.stub(AWS.config, 'update');
const { handler } = require('./');
await handler();
sinon.assert.calledWith(AWS.config.update, { region: 'us-west-2' });
sinon.assert.calledOnce(AWS.DynamoDB.DocumentClient);
sinon.assert.calledOnce(AWS.Lambda);
sinon.assert.calledWith(mLambda.invoke, {});
sinon.assert.calledOnce(mLambda.promise);
sinon.assert.calledWith(mDocumentClient.get, {});
sinon.assert.calledOnce(mDocumentClient.promise);
});
});
unit test results with 100% coverage:
61516053
✓ should pass (907ms)
1 passing (915ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Related
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
---------------|---------|----------|---------|---------|-------------------
I am using fastify framework for my node.js application and sequelize as an ORM. I am using mocha, chai, and Sinon for unit testing. I have to unit test my controller function. The following is the sample controller function.
// controllers.js;
const service = require('../services');
exports.create = (req, reply) => {
const attributes = req.body;
service.create(attributes)
.then((result) => {
reply.code(201).send(result);
})
.catch((error) => {
reply.send(error);
});
};
and my services file is as follows,
// services.js;
const { Model } = require('../models');
function create(attributes) {
return Model.create(attributes);
}
module.exports = { create };
In the above code, I want to unit test only the 'create' function in controllers.js. The problem is, it should not call the database, since it is unit testing. But the Model.create in service.js file will make a call to the database. How can I unit test controller function only?
You should stub service.create method and create mocked req, reply objects.
E.g.
controller.js:
const service = require('./service');
exports.create = (req, reply) => {
const attributes = req.body;
service
.create(attributes)
.then((result) => {
reply.code(201).send(result);
})
.catch((error) => {
reply.send(error);
});
};
service.js:
const { Model } = require('./models');
function create(attributes) {
return Model.create(attributes);
}
module.exports = { create };
models.js:
const Model = {
create() {
console.log('real implementation');
},
};
module.exports = { Model };
controller.test.js:
const controller = require('./controller');
const service = require('./service');
const sinon = require('sinon');
const flushPromises = () => new Promise(setImmediate);
describe('62536251', () => {
afterEach(() => {
sinon.restore();
});
it('should create', async () => {
const mResult = 'success';
sinon.stub(service, 'create').resolves(mResult);
const mReq = { body: {} };
const mReply = { code: sinon.stub().returnsThis(), send: sinon.stub() };
controller.create(mReq, mReply);
await flushPromises();
sinon.assert.calledWith(mReply.code, 201);
sinon.assert.calledWith(mReply.send, 'success');
});
it('should handle error', async () => {
const mError = new Error('network');
sinon.stub(service, 'create').rejects(mError);
const mReq = { body: {} };
const mReply = { code: sinon.stub().returnsThis(), send: sinon.stub() };
controller.create(mReq, mReply);
await flushPromises();
sinon.assert.calledWith(mReply.send, mError);
});
});
unit test result with coverage report:
62536251
✓ should create
✓ should handle error
2 passing (13ms)
---------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------|---------|----------|---------|---------|-------------------
All files | 83.33 | 100 | 60 | 83.33 |
controller.js | 100 | 100 | 100 | 100 |
models.js | 66.67 | 100 | 0 | 66.67 | 3
service.js | 66.67 | 100 | 0 | 66.67 | 4
---------------|---------|----------|---------|---------|-------------------
How do I test something like this?
const ssmParameterData = await ssm.getParameter(params, async (error, data) => {
if (error) throw error;
return data;
}).promise();
I have tried just mocking the method
spyOn(ssm, 'getParameter').and.returnValue(ssmParams);
and I get error like
TypeError: Cannot read property 'promise' of undefined
Here is the unit test solution:
index.js:
const AWS = require('aws-sdk');
const ssm = new AWS.SSM();
async function main(params) {
const ssmParameterData = await ssm
.getParameter(params, (error, data) => {
if (error) throw error;
return data;
})
.promise();
return ssmParameterData;
}
module.exports = { ssm, main };
index.test.js:
const { ssm, main } = require('./');
describe('60138152', () => {
it('should pass', async () => {
const data = 'fake data';
const getParameterRequestStub = { promise: jasmine.createSpy('promise') };
const getParameterStub = spyOn(ssm, 'getParameter').and.callFake((params, callback) => {
callback(null, data);
getParameterRequestStub.promise.and.resolveTo(data);
return getParameterRequestStub;
});
await expectAsync(main('test params')).toBeResolvedTo('fake data');
expect(getParameterStub).toHaveBeenCalledWith('test params', jasmine.any(Function));
expect(getParameterRequestStub.promise).toHaveBeenCalledTimes(1);
});
it('should throw error', async () => {
const mError = new Error('network');
const getParameterRequestStub = { promise: jasmine.createSpy('promise') };
const getParameterStub = spyOn(ssm, 'getParameter').and.callFake((params, callback) => {
callback(mError);
getParameterRequestStub.promise.and.rejectWith(mError);
return getParameterRequestStub;
});
await expectAsync(main('test params')).toBeRejectedWithError('network');
expect(getParameterStub).toHaveBeenCalledWith('test params', jasmine.any(Function));
});
});
unit test results with 100% coverage:
Executing 2 defined specs...
Running in random order... (seed: 87758)
Test Suites & Specs:
(node:93291) ExperimentalWarning: The fs.promises API is experimental
1. 60138152
✔ should pass (10ms)
✔ should throw error (1ms)
>> Done!
Summary:
👊 Passed
Suites: 1 of 1
Specs: 2 of 2
Expects: 5 (0 failures)
Finished in 0.034 seconds
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
source code: https://github.com/mrdulin/jasmine-examples/tree/master/src/stackoverflow/60138152
For the source code(dynamodb.js):
const AWS = require("aws-sdk");
const Promise = require("bluebird");
const client = new AWS.DynamoDB.DocumentClient();
module.exports.db = (method, params) => {
console.log("access dynamodb ");
return Promise.fromCallback(cb => client[method](params, cb));
};
Using the test that looks like this(dont want't to mock Promise.fromCallback):
describe("test", () => {
const realAWS = require("aws-sdk");
let fakePromise;
let fakeDynamo;
let dbClient;
beforeAll(function() {
fakePromise = jest.fn();
fakeDynamo = {
get: (params, cb) => {
fakePromise(params, cb);
}
};
realAWS.DynamoDB.DocumentClient = jest.fn(() => fakeDynamo);
dbClient = require("../dynamodb");
});
test.only("Test successed", done => {
let result = dbClient.db("get", null);
console.log("access dynamodb ");
expect(fakePromise).toHaveBeenCalled();
});
});
but when tun the test ,the error was heppend:
Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout.
if anyone can help me? Thanks!
You need to mock the implementation of the client.get method as a node callback style. So that Promise.fromCallback method will covert callback style to a promise.
Besides, you need to trigger the callback in your test case. That's why you got a timeout error.
E.g.
dynamodb.js:
const AWS = require('aws-sdk');
const Promise = require('bluebird');
const client = new AWS.DynamoDB.DocumentClient();
module.exports.db = (method, params) => {
console.log('access dynamodb');
return Promise.fromCallback((cb) => client[method](params, cb));
};
dynamodb.test.js:
const { db } = require('./dynamodb');
const AWS = require('aws-sdk');
jest.mock('aws-sdk', () => {
const mClient = { get: jest.fn() };
const mDynamoDB = {
DocumentClient: jest.fn(() => mClient),
};
return { DynamoDB: mDynamoDB };
});
const mockClient = new AWS.DynamoDB.DocumentClient();
describe('54360588', () => {
afterAll(() => {
jest.resetAllMocks();
});
it('should pass', async () => {
mockClient.get.mockImplementationOnce((err, callback) => {
callback(null, 'fake data');
});
const actual = await db('get', null);
expect(actual).toBe('fake data');
expect(mockClient.get).toBeCalledWith(null, expect.any(Function));
});
});
unit test result with coverage report:
PASS src/stackoverflow/54360588/dynamodb.test.js (10.74s)
54360588
✓ should pass (28ms)
console.log src/stackoverflow/54360588/dynamodb.js:177
access dynamodb
-------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
dynamodb.js | 100 | 100 | 100 | 100 | |
-------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 12.636s
I am trying to write unit tests but am having trouble stubbing the AWS S3 getobject method. Here is my code:
describe('testExecuteSuccess()', function () {
it('Test execution with id is successful.', async () => {
let id = "test_id";
const getObjectStub = AWS.S3.prototype.getObject = sinon.stub();
getObjectStub.returns({ promise: () => Promise.resolve({ Body: "test" }) });
await executionHandler.execute(id).then(() => {
getObjectStub.should.have.been.calledOnce;
});
});
});
Does anyone know what is wrong with it/how to properly stub the getObject method? When I run the test, I am getting InvalidParameterType: Expected params.Bucket to be a string which proves that the stub is not working.
Here is the code to the executionHandler.execute method:
exports.execute = async function(curr_id) {
let params = { Bucket: BUCKET_NAME, Key: KEY_PATH }
let fileObject = await s3.getObject(params).promise();
let codeId = executeCode(fileObject).id;
if (codeId !== curr_id) {
throw "Id from executed code does not match currentId: " + curr_id;
}
}
Note: I am using Mocha test runner.
You can stub out dependencies such as aws-sdk module with link seams. This is the CommonJS version, so we will be using proxyquire to construct our seams.
unit test solution:
main.js:
const AWS = require('aws-sdk');
const s3 = new AWS.S3();
exports.execute = async function (curr_id) {
const BUCKET_NAME = 'examplebucket';
const KEY_PATH = 'SampleFile.txt';
let params = { Bucket: BUCKET_NAME, Key: KEY_PATH };
let fileObject = await s3.getObject(params).promise();
let codeId = executeCode(fileObject).id;
if (codeId !== curr_id) {
throw 'Id from executed code does not match currentId: ' + curr_id;
}
};
function executeCode(file) {
return file;
}
main.test.js:
const proxyquire = require('proxyquire');
const sinon = require('sinon');
const chai = require('chai');
const chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
const { expect } = chai;
describe('51959840', () => {
afterEach(() => {
sinon.restore();
});
it('should do nothing if codeId is equal with curr_id', async () => {
const fileObject = { id: '1' };
const s3Mock = {
getObject: sinon.stub().returnsThis(),
promise: sinon.stub().resolves(fileObject),
};
const AWSMock = { S3: sinon.stub().returns(s3Mock) };
const { execute } = proxyquire('./main', {
'aws-sdk': AWSMock,
});
await execute('1');
sinon.assert.calledOnce(AWSMock.S3);
sinon.assert.calledWithExactly(s3Mock.getObject, { Bucket: 'examplebucket', Key: 'SampleFile.txt' });
sinon.assert.calledOnce(s3Mock.promise);
});
it('should throw error if codeId is NOT equal with curr_id', async () => {
const fileObject = { id: '2' };
const s3Mock = {
getObject: sinon.stub().returnsThis(),
promise: sinon.stub().resolves(fileObject),
};
const AWSMock = { S3: sinon.stub().returns(s3Mock) };
const { execute } = proxyquire('./main', {
'aws-sdk': AWSMock,
});
await expect(execute('1')).to.rejectedWith('Id from executed code does not match currentId: 1');
sinon.assert.calledOnce(AWSMock.S3);
sinon.assert.calledWithExactly(s3Mock.getObject, { Bucket: 'examplebucket', Key: 'SampleFile.txt' });
sinon.assert.calledOnce(s3Mock.promise);
});
});
unit test result:
51959840
✓ should do nothing if codeId is equal with curr_id (2884ms)
✓ should throw error if codeId is NOT equal with curr_id
2 passing (3s)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
main.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
package versions:
"proxyquire": "^2.1.3",
"sinon": "^8.1.1",
"aws-sdk": "^2.817.0",