繁体   English   中英

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

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

背景

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

问题

现在我开发了大约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失败测试用例的正确方法呢?

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

您可以返回一个promise,或者等待lambdalocal.execute ,然后执行断言,而不是使用callback参数。

例如(使用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文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM