使用 jest 和 NodeJsFunction 的 CDK 单元测试

CDK Unit test using jest and NodeJsFunction

我在尝试为我的 CDK 项目写入单元时遇到问题。

正在创建堆栈,非常简单:

-> APIGateway (Rest)
  -> POST endpoint pointing to lambda
-> Lambda

我的单位很简单:

describe("Test WebhookProxyStack", () => {
  it("template must be defined", () => {
    const app = new cdk.App();
    const processorStack = new WebhookProxyStack(app, "dev" as never);
    const template = Template.fromStack(processorStack);
    expect(template).toBeDefined();
  });
});

Lambda 代码是

const lambda = new NodejsFunction(scope, name, {
    runtime: Runtime.NODEJS_14_X,
    handler: `handler`,
    entry: require.resolve(
      "@webhook-proxy/src/XXX.ts",
    ),
  });

当我部署 CDK 时,一切都很好地捆绑(通过本地 esbuild),没有错误,但是当尝试 运行 这个单元时,我收到如下错误:

Error: Failed to bundle asset WebhookProxy-dev/lambda-name/Code/Stage, bundle output is located at /private/var/folders/g_/7s34q40s3rg40280qhrvx5fm0000gn/T/cdk.outQhujdM/bundling-temp-1309d84e2e3633714893bccef1ab36748a1c6088468eb4607da3325bcd2d7058-error: Error: bash -c yarn run esbuild --bundle "{OUTPUT_PATH}" --target=node14 --platform=node --outfile="/private/var/folders/g_/7s34q40s3rg40280qhrvx5fm0000gn/T/cdk.outQhujdM/bundling-temp-1309d84e2e3633714893bccef1ab36748a1c6088468eb4607da3325bcd2d7058/index.js" --external:aws-sdk run in directory {PROJECT_PATH} exited with status 127

at AssetStaging.bundle (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/core/lib/asset-staging.ts:395:13)
at AssetStaging.stageByBundling (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/core/lib/asset-staging.ts:243:10)
at stageThisAsset (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/core/lib/asset-staging.ts:134:35)
at Cache.obtain (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/core/lib/private/cache.ts:24:13)
at new AssetStaging (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/core/lib/asset-staging.ts:159:44)
at new Asset (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/aws-s3-assets/lib/asset.ts:72:21)
at AssetCode.bind (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/aws-lambda/lib/code.ts:180:20)
at new Function (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/aws-lambda/lib/function.ts:348:29)
at new NodejsFunction (/Users/XXX/Sites/XXX/webhook-proxy/node_modules/aws-cdk-lib/aws-lambda-nodejs/lib/function.ts:50:5)

任何 hint\help 将此 lambda 捆绑到单位时可能有什么问题以及如何传递它?

另一个问题是为什么在执行单元时必须构建这个 lambda?

信息:

构建 Lambda 时测试 Esbuild 错误

不是修复,而是 diagnostic/workaround:在 lambda 道具中传递 bundling: {forceDockerBundling: true } 以使用 Docker 而不是 esbuild for local bundling

为什么在执行单元时构建 lambda?

堆栈需要合成才能进行测试。 CDK generates a hash for assets 作为合成过程的一部分。源哈希“在构建时用于确定资产的内容是否已更改。”