ServerlessSpy

CDK Construct - ServerlessSpy

CDK Construct

Adding ServerlessSpy construct is super simple.

Step 1: Create object:

const serverlessSpy = new ServerlessSpy(this, 'ServerlessSpy', {
  generateSpyEventsFileLocation: 'serverlessSpyEvents/ServerlessSpyEvents.ts'              
});

Parameters:

  • generateSpyEventsFileLocation: serverlessSpyEvents/ServerlessSpyEvents.ts
    It is a TypeScript file that will be generated by CDK construct. It will make your tests strongly typed 💪. It just contains an interface with a list of possible events, but thanks to this file and the magic of TypeScript, every test becomes strongly typed.

  • debugMode: true
    Enable debug mode.

  • spySqsWithNoSubscriptionAndDropAllMessages.
    If no Lambda is subscribed to SQS, the ServerlessSpy can not intercept events. With this flag on, additional Lambda will be created that will just consume messages and throw them away (= lost forever ⛔). Of course, that is undesirable in most cases, but it could be useful for some tests.

Step 2: Star spying

You can spy on everything:

serverlessSpy.spy();

or you can limit what to spy on:

serverlessSpy.spy({
  spyLambda: true,
  spySqs: true,
  spySnsTopic: true,
  spySnsSubsription: true,
  spyEventBridge: true,
  spyEventBridgeRule: true,
  spyS3: true,
  spyDynamoDB: true,
});

You can also specify just some nodes

serverlessSpy.spyNodes([...]);

All child nodes are also included in the spying.

You can mix and match both methods.

Why would you exclude some of the nodes? For DynamoDB, there could be only two Lambdas subscribed to DynamoDB Streams, and S3 can only have one. If you reach the quotas with your primary stack, you can not use ServerlessSpy on those resources.

There could also be other reasons to exclude some of the nodes specific to your use case.