gpt4 book ai didi

node.js - 如何在 Nodejs 上使用 DynamoDb 测试等待/异步?

转载 作者:行者123 更新时间:2023-12-02 05:46:46 26 4
gpt4 key购买 nike

我使用 NodeJs 实现 AWS Lambda 函数,并想澄清测试与 DynamoDB 集成的正确方法是什么:

Lambda 代码:

const AWS = require('aws-sdk');

AWS.config.update({region: region});
const dynamoDb = new AWS.DynamoDB();

exports.handler = async function(event, context) {
...
await dynamoDb.deleteItem(item).promise();
}

我打算使用 mocha、sinon、chai 和 aws-sdk-mock 进行测试:

const expect = require('chai').expect;
const AWS = require('aws-sdk-mock');
const lambda = require('../index.js');
const sinon = require('sinon');

describe('Test', function () {
let deleteItemSpy;

beforeEach(function () {
deleteItemSpy = sinon.spy();
AWS.mock('DynamoDB', 'deleteItem', deleteItemSpy);
}
it('valid call', async function() {
await lambda.handler({"id":1}, null);
expect(deleteItemSpy.calledOnce).to.be.true;
})
});

但是有两个主要问题:

  1. 如果 dynamoDb 是在处理程序外部创建的,则模拟不起作用。我还有什么其他选择?我可以以某种方式使用 sinon.stub 吗?

  2. 它会抛出超时,因为 await 从未收到来自 lambda 的结果。问题与 spy 本身有关。我可能可以将其替换为: AWS.mock('DynamoDB', 'deleteItem', function (params, callback) { });

最佳答案

好吧,我明白了。不确定这是否是最好的方法,但它确实有效。

const expect = require('chai').expect;
const AWS = require('aws-sdk');
const sinon = require('sinon');

describe('Test', function () {
let deleteItemStub;
let mockDynamoDb;
let lambda;

before(function() {
deleteItemStub = sinon.stub();
mockDynamoDb = sinon.stub(AWS, 'DynamoDB').callsFake(function() {
return {
deleteItem: deleteItemStub
};
});
lambda = require('../index.js');
});
after(function () {
mockDynamoDb.restore();
});

beforeEach(function () {
deleteItemStub.returns({ promise: () => Promise.resolve() });
});

afterEach(function () {
deleteItemStub.reset();
});
it('valid call', async function() {
await lambda.handler({"id":1}, null);
expect(deleteItemStub.calledOnce).to.be.true;
});
});

关于node.js - 如何在 Nodejs 上使用 DynamoDb 测试等待/异步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51033523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com