如何对包含 dynamoDB 查询的 lambda 函数进行单元测试

How to unit test a lambda function that includes a dynamoDB query

我在我的 Alexa 技能的 lambda 函数中有一个函数,我正在尝试使用 aws-lambda-mock-context 节点包进行单元测试。我尝试测试的方法包括调用 DynamoDB 以检查我的 table 中是否存在项目。

目前,我的测试立即失败并显示 CredentialsError: Missing credentials in config。在 this blog 之后,我尝试将我的 Amazon IAM 凭据手动输入到 .aws/credentials 文件中。使用凭据进行测试导致测试 运行 超过 30 秒,然后超时,DynamoDB 没有成功或失败的结果。我不知道从这里去哪里。

我要进行单元测试的函数如下所示:

helper.prototype.checkForItem = function(alexa) {
  var registration_id = 123;
  var params = {
    TableName: 'registrations',
    Key: {
      id: {"N" : registration_id}
    }
  };

  return this.getItemFromDB(params).then(function(data) {
    //...
  }

以及对 DynamoDB 的调用:

helper.prototype.getItemFromDB = function(params) {
  return new Promise(function(fulfill, reject) {
    dynamoDB.getItem(params, function(err, data) {
      if (err == null) {
        console.log("fulfilled");
        fulfill(data);
      }
      else {
        console.log("error recieving data " + err);
        reject(null);
      }
    });
  });
} 

如果您想进行单元测试,您可以使用任何模拟库(如 nock)来模拟 dynamo db 端点,您还可以检查 fiddler 请求/响应您的应用程序对 dynamo db 端点所做的操作,然后您可以相应地进行故障排除。

您可以使用 SAM Local 来测试您的 lambda:

AWS SAM is a fast and easy way of deploying your serverless applications, allowing you to write simple templates to describe your functions and their event sources (Amazon API Gateway, Amazon S3, Kinesis, and so on). Based on AWS SAM, SAM Local is an AWS CLI tool that provides an environment for you to develop, test, and analyze your serverless applications locally before uploading them to the Lambda runtime. Whether you're developing on Linux, Mac, or Microsoft Windows, you can use SAM Local to create a local testing environment that simulates the AWS runtime environment. Doing so helps you address issues such as performance. Working with SAM Local also allows faster, iterative development of your Lambda function code because there is no need to redeploy your application package to the AWS Lambda runtime. For more information, see Building a Simple Application Using SAM Local.