首页 > 解决方案 > 如何对 AWS Lambda 使用 lambda-local 和 mocha 进行单元测试?

问题描述

背景

我正在开发一个使用带有serverless -appsync-plugin 的无服务器框架 构建的项目。我实现了一个端点(AWS Lambda)来处理 Appsync 通过 graphQL 生成的所有请求。端点会将请求路由到相应的函数以执行操作。

问题

现在我已经开发了大约 10 多个操作,我想自动化单元测试的过程。为简单起见,我决定在本地将单个端点作为 lambda 运行以进行所有测试(而不是运行 appsync-offline)。

因此,我将lambda-localmocha一起使用。但是,根据我从 lambda 得到的响应,我无法让测试用例失败。

it('db should have a user of uId: 123',  async function () {
  lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath,
    callback: function(err, data) {
      if(err) {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
      } else {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here too
      }
    }
  });
  console.log(3)
})

在这两种情况下,我都希望它失败,它不会使任何一个callback('failed', null)callback(null, 'success').

那么,使 lambda-local 测试用例失败的正确方法是什么?

标签: unit-testinglambdaaws-lambdamocha.js

解决方案


在您的代码中,测试完成而没有 mocha 注册断言lambdaLocal.execute失败。所以总会过去的。

除了使用回调参数,您还可以返回一个承诺,或者等待lambdalocal.execute然后执行您的断言。

例如(使用承诺):

it('db should have a user of uId: 123',  function () {
  return lambdaLocal.execute({
    event: makeUserEvent({userId: '123'}),
    callbackWaitsForEmptyEventLoop: false,
    lambdaPath })
 .then(
    (data) => {
        console.log(2)
        // some checking here, may fail or may not fail
        expect.fail(null, null, 'return fail if the userId is 234') //should fail here
    },
    (err) => {
        console.log(1)
        expect.fail(null, null, 'You are not supposed to be here') //should fail here
    })
}

或者更改传递给的函数的签名it以获取附加参数(通常称为done),然后 mocha 将使用该参数来传递可用于表示测试已完成的函数。有关更多信息,请参阅mocha 文档


推荐阅读