如何使用 lambda-local 和 mocha 对 AWS Lambda 进行单元测试?

How to unit-test a AWS Lambda use lambda-local with mocha?

背景

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

问题

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

所以,我用了lambda-local with mocha。但是,根据我从 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 无法通过测试用例的正确方法是什么?

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

您可以 return 承诺,或者等待 lambdalocal.execute 然后执行断言,而不是使用回调参数。

例如(使用 Promises):

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 documentation