Quick Start
March 10, 2024 ยท View on GitHub
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();
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();
});
Step 5: Start local web console to gain more insights ๐ต
npx sspy --cdkoutput cdkOutput.json