I have an endpoint in API Gateway that maps to a Lambda function in AWS. When writing test cases for the new handler function for the endpoint, I don't want the spec file to call the actual API or connect to DynamoDB. I tried adding sinon.stub
but it still calls connect to DynamoDB and the test case fails. I can't find where the stub goes wrong.
Handler.js:
saveUser(userName, logger) { const Item = { id: uuid.v4(), userName, ttl: parseInt(Date.now() / 1000) + 900 // expire the name after 15 minutes from now }; const params = { TableName: "my-table-name", Item }; logger.log(`Saving new user name to DynamoDB: ${JSON.stringify(params)}`); return new Promise(function(resolve, reject) { db.put(params, function(err, _) { if (err) { logger.exception(`Unable to connect to DynamoDB to create: ${err}`); reject({ statusCode: 404, err }); } else { logger.log(`Saved data to DynamoDB: ${JSON.stringify(Item)}`); resolve({ statusCode: 201, body: Item }); } }); }); }
Handler.spec.js:
import AWS from "aws-sdk"; const db = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); describe("user-name-handler", function() { const sandbox = sinon.createSandbox(); afterEach(() => sandbox.restore()); it("Test saveUser() method", async function(done) { const { saveUser } = userHandler; sandbox.stub(db, "put") .returns(new Promise((resolve, _) => resolve({ statusCode: 200 }))); try { const result = await saveUser("Sample User", { log: () => {}, exception: () => {} }); expect(result).to.be.equal({ data: "some data" }); done(); } catch (err) { console.log(err); done(); } }); });
mistake:
Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.
I logged the err
object via the console and it gave me this error, which makes me think it's trying to connect to DynamoDB.
Error: connect ENETUNREACH 127.0.0.1:80 at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16) { message: 'Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1', errno: 'ENETUNREACH', code: 'CredentialsError', syscall: 'connect', address: '127.0.0.1', port: 80, time: 2023-05-07T10:45:25.835Z, originalError: { message: 'Could not load credentials from any providers', errno: 'ENETUNREACH', code: 'CredentialsError', syscall: 'connect', address: '127.0.0.1', port: 80, time: 2023-05-07T10:45:25.835Z, originalError: [Object] }
Related: How to test methods that return data from AWS DynamoDB
P粉7147807682024-03-22 18:19:12
You are mocking the db
declared in the test file - not the saveUser
that is actually used.
The solution is to move the db declaration to its own module, for example: db.js
const AWS = require("aws-sdk"); const db = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); module.exports = db;
Then import it from the
saveUser module and test - this way we can mock the same db
instance that saveUser
is using.
I was able to successfully run the test using the following code:
Test code:
const sinon = require('sinon'); const { saveUser } = require('../userHandler'); const { expect } = require('chai'); const db = require('../db'); describe('user-name-handler', function() { afterEach(() => sinon.restore()); it('Test saveUser() method', async function() { sinon.stub(db, 'put') .returns(new Promise((resolve, _) => resolve({ statusCode: 201, body: 'some data' }))); try { const result = await saveUser(db, 'Sample User', { log: () => {}, exception: () => {} }); expect(result).to.deep.equal({ statusCode: 201, body: 'some data' }); } catch (err) { console.log('err', err); } }); });
User handler file:
const db = require('./db'); const saveUser = (db, userName, logger) => { const Item = { id: uuid.v4(), userName, ttl: parseInt(Date.now() / 1000) + 900 // expire the name after 15 minutes from now }; const params = { TableName: "my-table-name" }; logger.log(`Saving new user name to DynamoDB: ${JSON.stringify(params)}`); return db.put(params, function(err, _) { if (err) { logger.exception(`Unable to connect to DynamoDB to create: ${err}`); return reject({ statusCode: 404, err }); } else { logger.log(`Saved data to DynamoDB: ${JSON.stringify(Item)}`); return resolve({ statusCode: 201, body: Item }); } }); } module.exports = { saveUser };
package.json
{ "name": "play", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "mocha --timeout 5000" }, "author": "", "license": "ISC", "dependencies": { "aws-sdk": "^2.1373.0", "chai": "^4.3.7", "mocha": "^10.2.0", "sinon": "^15.0.4" } }Output
P粉4760461652024-03-22 16:16:37
We can separate the database connection into a different file and import it into the handler implementation as well as the spec file.
db.js
import AWS from "aws-sdk"; const db = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" }); export default db;
yields()
Function The stub should not return a Promise
directly, but should be chained with the arguments that .yields()
and its callbacks will accept. We can change parameters to cover various branches of the code.
describe("user-handler connection success", function () { const sandbox = sinon.createSandbox(); afterEach(() => sandbox.restore()); before(() => { sinon.stub(db, "put") .yields(null, true); sinon.stub(db, "get") .yields(null, { sampleKey: "sample value" }); sinon.stub(db, "delete") .yields(null, { sampleKey: "sample value" }); }); after(() => { db.put.restore(); db.get.restore(); db.delete.restore(); }); it("Test saveUser() method success", async function () { const result = await userHandler.saveToken("sample user", { log: () => {}, exception: () => {} }); expect(result.statusCode).to.be.equal(201); }); });
https://www.youtube.com/watch?v=vXDbmrh0xDQ