0

I am trying to use sinon to test a piece of code that is using an DynamoDB SDK method batchGet. Below the code:

const fetchSingleUser = async (userId) => {
    try {
        let queryParams = {RequestItems: {}};
        queryParams.RequestItems['users'] = {
            Keys: [{'UserId': userId}],
            ProjectionExpression: 'UserId,Age,#UserName',
            ExpressionAttributeNames: {'#UserName': 'Name'}
        };
        const res = await docClient.batchGet(queryParams).promise();
        return res.Responses.users[0];
    } catch (e) {
        console.log('users::fetch::error - ', e);
    }
};

Below the test using sinon:

'use strict';

const sinon = require('sinon');
const proxyquire = require('proxyquire').noCallThru();
let assert = require('assert');

describe('DynamoDB Mock Test', function () {
    let AWS;
    let scriptToTest;
    let batchGetFunc;

    before(function () {
        batchGetFunc = sinon.stub();

        AWS = {
            DynamoDB: {
                DocumentClient: sinon.stub().returns({
                    batchGet: batchGetFunc
                })
            }
        };

        scriptToTest = proxyquire('../index', {
            'aws-sdk': AWS
        });
    });

    it('Should scan using async/await and promise', async function () {
        let result = { UserId: 'segf876seg876', Age: 33, Name: 'Paul' }
        
        batchGetFunc.withArgs(sinon.match.any).returns({
            promise: () => result
        });

        const data = await scriptToTest.fetchSingleUser('segf876seg876');
        console.log('--data: ', data)
        assert.equal(data.UserId, 'segf876seg876');
    });

});

The Problem:

const data = await scriptToTest.fetchSingleUser('segf876seg876') always returns 'undefined'

2
  • Do you get any error message from ` console.log('users::fetch::error - ', e);`? Commented Jul 3, 2020 at 7:36
  • It says "TypeError: Cannot read property 'users' of undefined", since const res did't get any data from await. Commented Jul 3, 2020 at 7:53

1 Answer 1

1

Function fetchSingleUser always returns 'undefined' because you do not return anything after catch (after error happens). You only define return value on success.

But why errors happens, because const res does not contain Responses.users[0].

Simple solution:

change let result = { UserId: 'segf876seg876', Age: 33, Name: 'Paul' } to satisfy code Responses.users[0] to

const result = {
    Responses: {
        users: [{ UserId: 'segf876seg876', Age: 33, Name: 'Paul' }],
      },
    };

Note: use const if you not change variable value.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.