unit-testing - 如何对 AWS Lambda 使用 lambda-local 和 mocha 进行单元测试?
问题描述
背景
我正在开发一个使用带有serverless -appsync-plugin 的无服务器框架 构建的项目。我实现了一个端点(AWS Lambda)来处理 Appsync 通过 graphQL 生成的所有请求。端点会将请求路由到相应的函数以执行操作。
问题
现在我已经开发了大约 10 多个操作,我想自动化单元测试的过程。为简单起见,我决定在本地将单个端点作为 lambda 运行以进行所有测试(而不是运行 appsync-offline)。
因此,我将lambda-local与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
失败。所以总会过去的。
除了使用回调参数,您还可以返回一个承诺,或者等待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 文档。
推荐阅读
- javascript - 将UTC转换为特定时区时间Javascript
- arrays - 查找列表中所有可能的项目组合,放入更大尺寸的列表中
- python - 为什么 urlopen 给出响应 200 而请求给出 403?
- css - 可以在@media 中将 min-width 和 max-width 设置为相同的值吗?
- google-chrome - Chrome默认弹出窗口位置和大小
- excel - 如何将相同名称(字符串)的相同ID(如密集排名)分配给Excel中的字符字段
- docker - 如何设置 Azure Pipelines 以使用多个 docker 容器发布到 Azure App Service?
- docker - nginx:在上游找不到 [emerg] 主机 :: 代理 api 调用?
- python-3.x - 使用带有布尔文字错误的身份比较
- google-apps-script - 有没有办法检测谷歌表格中的点击并运行函数?