ServerlessSpy

Quick Start - ServerlessSpy

Quick Start

ServerlessSpy is meant for the following environments:

  • Development environment: So you can write tests. The web console helps you gain insight into what is happening in the system.
  • Automatic test environment: You execute written tests in CI/CD.

Step 1: Install

npm install serverless-spy

Step 2: Include ServerlessSpy in the CDK stack

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

more

Step 3: Deploy CDK stack with exporting CloudFormation outputs

cdk deploy --outputs-file cdkOutput.json

The key part of the output is ServerlessSpyWsUrl, which is the URL to the WebSocket where the testing library and web console receive events. Exclude the cdkOutput.json file from git (like you always do), especially if it has secrets.

Apart from CF output, ServerlessSpy generates the TypeScript file serverlessSpyEvents/ServerlessSpyEvents.ts specified in the first step. This makes your tests strongly typed 💪 thanks to TypeScript.

Step 4: Write tests 🔨

Initialize the ServerlessSpyListener

import { ServerlessSpyEvents } from '../serverlessSpyEvents/ServerlessSpyEvents';

let serverlessSpyListener: ServerlessSpyListener<ServerlessSpyEvents>;
beforeEach(async () => {
  serverlessSpyListener =
    await createServerlessSpyListener<ServerlessSpyEvents>({
      ServerlessSpyWsUrl: output.ServerlessSpyWsUrl, // ServerlessSpy IoT URL from CloudFormation output
    });
});

Write test:

(
  await serverlessSpyListener.waitForSnsTopicMyTopic<TestData>()
).toMatchObject({ message: data });

Close the ServerlessSpyListener

afterEach(async () => {
  serverlessSpyListener.stop();
});

more

Step 5: Start local web console to gain more insights 🕵

npx sspy --cdkoutput cdkOutput.json

more