【问题标题】:DynamoDB SDK async function returns undefined when using sinonDynamoDB SDK 异步函数在使用 sinon 时返回 undefined
【发布时间】:2020-10-23 21:09:31
【问题描述】:

我正在尝试使用 sinon 来测试一段使用 DynamoDB SDK 方法 batchGet 的代码。代码下方:

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);
    }
};

下面使用 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');
    });

});

问题:

const data = await scriptToTest.fetchSingleUser('segf876seg876') 总是返回 'undefined'

【问题讨论】:

  • 您是否从`console.log('users::fetch::error - ', e);`收到任何错误消息?
  • 它说“TypeError: Cannot read property 'users' of undefined”,因为 const res 没有从 await 获取任何数据。

标签: amazon-web-services amazon-dynamodb mocha.js sinon


【解决方案1】:

函数 fetchSingleUser 总是返回“未定义”,因为在 catch 之后(发生错误后)您不会返回任何内容。你只定义成功的返回值。

但是为什么会出现错误,因为const res 不包含Responses.users[0]

简单的解决方案

let result = { UserId: 'segf876seg876', Age: 33, Name: 'Paul' }更改为满足代码Responses.users[0]

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

注意:如果不更改变量值,请使用 const

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 2019-08-30
    • 2019-01-27
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多