1

I am using jest for testing and I have a lambda function in my Stack I want to test. Like this:

const lambda = new lambda.Function(this, "MyLambda", {
   ...
   code: lambda.Code.fromAsset("../assets/lambda.zip"),
   ...
   }
);

I want to test some of the properties but also if the lambda is in the stack. But when I run the test it complains that my lambda.zip doesn't exist. Which is fair enough, as it's built as part of the another build job. Is there any way to inject or somehow mock the lambda's asset.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

3 Answers3

0

You can try using Code.fromInline() as it doesn't require any files on disk. Simply pass a dummy function code as a string.

lambda.Code.fromInline("exports.handler = async function(event, context) {}")
kichik
  • 33,220
  • 7
  • 94
  • 114
0

Based on kichik's idea to use Code.fromInline(), this worked for me:

import { InlineCode } from "@aws-cdk/aws-lambda"

jest.mock("@aws-cdk/aws-lambda", () => ({
  ...jest.requireActual("@aws-cdk/aws-lambda"),
  Code: {
    fromAsset: () => new InlineCode("foo"),
  },
}))

Probably can be simplified with jest.spyOn, but I couldn't figure out how to make it work.

0

In a lot of simple scenarios, there's no need to bother with a complicated jest mocking.

beforeAll(() => {
  Object.defineProperty(Code, 'fromAsset', {
    value: () => Code.fromInline('test code'),
  });
});
astef
  • 8,575
  • 4
  • 56
  • 95