Last active
October 5, 2021 19:41
-
-
Save jonathanws/d7aa0b2b38e9b787c736a06c0d575cb9 to your computer and use it in GitHub Desktop.
Testing AWS services with Sinon mocks in Lambda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Writing tests for functions that use external dependencies is tough. | |
* We can get past this by using sinon sandboxes to temporarily overwrite the | |
* prototypes of those dependencies, just for testing | |
* | |
* Before running these tests run: | |
* $ npm install --save-dev aws-sdk sinon mocha | |
*/ | |
/** | |
* index.js - The file to be tested | |
*/ | |
const { DynamoDB } = require('aws-sdk') | |
const dynamoDB = new DynamoDB.DocumentClient() | |
exports.handler = async (event) => { | |
let result | |
const params = { | |
TableName: 'Tasks', | |
Key: { id: event.pathParameters.id } | |
} | |
try { | |
result = (await dynamoDB.get(params).promise()).Item | |
} catch (e) { | |
result = { error: 'task not found' } | |
} | |
return result | |
} | |
/** | |
* index.spec.js - The test file that tests index.js | |
*/ | |
const assert = require('assert') // Built in node library, no need to install | |
const sinon = require('sinon') | |
const { DynamoDB } = require('aws-sdk') | |
const { handler } = require('./index.js') | |
// create a sinon sandbox | |
const sandbox = sinon.createSandbox() | |
describe('Test my lambda', () => { | |
describe('#handler()', () => { | |
beforeEach(() => sandbox | |
// Here I overwrite every call to #get() | |
.stub(DynamoDB.DocumentClient.prototype, 'get') | |
// And define my own return | |
.returns({ | |
// promise function is required here because we use the | |
// #AWS.request.promise() syntax in the handler (line 24) | |
promise: () => ({ Item: { id: 42 } }) | |
}) | |
) | |
// Runs after every test. Undo our temporary | |
// overwrite so the next test starts clean | |
afterEach(() => sandbox.restore()) | |
it('gets a task from the database', async () => { | |
const response = await handler({ pathParameters: { id: 42 } }) | |
assert.strictEqual(response.id, 42) | |
}) | |
}) | |
}) | |
// and finally, run your mocha tests. I'm using babel, so I set things up with: | |
// $ npm install --save-dev @babel/core @babel/preset-env @babel/register | |
// | |
// and then I run all tests with mocha by calling: | |
// $ ./node_modules/.bin/mocha index.spec.js -- require @babel/register | |
// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment