Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create get all events util and rename getEvents to getEvent #33

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 46 additions & 39 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,45 +36,45 @@ sls-test-tools is currently being actively maintained, yet is in alpha. Your fee

### EventBridge

```
expect(eventBridgeEvents).toHaveEvent();
```ts
expect(eventBridgeEvents).toHaveEvent();

expect(eventBridgeEvents).toHaveEventWithSource("order.created");
expect(eventBridgeEvents).toHaveEventWithSource("order.created");
```

### S3

Note: these async assertions require "await"

```
await expect("BUCKET NAME").toHaveS3ObjectWithNameEqualTo("FILE NAME");
```ts
await expect("BUCKET NAME").toHaveS3ObjectWithNameEqualTo("FILE NAME");
```

```
await expect("BUCKET NAME").toExistAsS3Bucket();
```ts
await expect("BUCKET NAME").toExistAsS3Bucket();
```

```
await expect({
bucketName: "BUCKET_NAME",
objectName: "FILE NAME",
}).toHaveContentTypeEqualTo("CONTENT_TYPE");;
```ts
await expect({
bucketName: "BUCKET_NAME",
objectName: "FILE NAME",
}).toHaveContentTypeEqualTo("CONTENT_TYPE");
```

where CONTENT_TYPE are [standards MIME types](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types)

```
await expect({
bucketName: "BUCKET_NAME",
objectName: "FILE NAME",
}).toHaveContentEqualTo("CONTENT");
```ts
await expect({
bucketName: "BUCKET_NAME",
objectName: "FILE NAME",
}).toHaveContentEqualTo("CONTENT");
```

### Step Functions

Note: these assertions also require "await"

```
```ts
await expect("STATE_MACHINE_NAME").toHaveCompletedExecutionWithStatus("STATUS");
await expect("STATE_MACHINE_NAME").toMatchStateMachineOutput({EXPECTED_OUTPUT}));
```
Expand All @@ -83,11 +83,9 @@ Note: these assertions also require "await"

Note: these assertions also require "await"

```
await expect("TABLENAME").toContainItemWithValues({[field]: value});
await expect({PK: pk,
SK: sk,
}).toExistInDynamoTable('TABLENAME');
```ts
await expect("TABLENAME").toContainItemWithValues({ [field]: value });
await expect({ PK: pk, SK: sk }).toExistInDynamoTable("TABLENAME");
```

### Cognito
Expand All @@ -104,9 +102,9 @@ Note: this assertion also requires "await"

AWSClient - An AWS client with credentials set up

```
getStackResources(stackName) - get information about a stack
getOptions() - get options for making requests to AWS
```ts
getStackResources(stackName); // get information about a stack
getOptions(); // get options for making requests to AWS
```

### EventBridge
Expand All @@ -115,17 +113,18 @@ An interface to the deployed EventBridge, allowing events to be injected and int

#### Static

```
EventBridge.build(busName) - create a EventBridge instance to allow events to be injected and intercepted
```ts
EventBridge.build(busName); // create a EventBridge instance to allow events to be injected and intercepted
```

#### Instance

```
eventBridge.publishEvent(source, detailType, detail) - publish an event to the bus
eventBridge.getEvents() - get the events that have been sent to the bus
eventBridge.clear() - clear old messages
eventBridge.destroy() - remove infastructure used to track events
```ts
eventBridge.publishEvent(source, detailType, detail); // publish an event to the bus
eventBridge.getLastEvent(); // get the last event that has been sent to the bus
eventBridge.getAllEvents(); // get all the events that have been sent to the bus
eventBridge.clear(); // clear old messages
eventBridge.destroy(); // remove infastructure used to track events
```

### Step Functions
Expand All @@ -134,18 +133,26 @@ An interface to a deployed Step Function, with a function to execute a Step Func

#### Static

```
StepFunctions.build() // create a Step Functions Client for executing existing state machines
```ts
StepFunctions.build(); // create a Step Functions Client for executing existing state machines
```

#### Instance

```
stepFunctions.runExecution(stateMachineName, input) // executes state machine until completion
```ts
stepFunctions.runExecution(stateMachineName, input); // executes state machine until completion
```

## Running with `jest`

### Setup

We recommend that you differentiate your unit tests from your integration tests by using two distinct Jest configurations: `jest.config.json` and `jest.integration.config.json`. In particular, in the configuration file of the integration tests, it is imperative to exclude any mocked AWS services by using:

```json
modulePathIgnorePatterns: ["__mocks__"];
```

### Arguments

- When running tests with `jest` using `sls-test-tools` matchers there are certain parameters needed for `sls-test-tools` to make assertions.
Expand All @@ -165,7 +172,7 @@ An interface to a deployed Step Function, with a function to execute a Step Func

- To avoid issues we recommend `--runInBand`

```
```ts
import { AWSClient, EventBridge } from "sls-test-tools";

const lambda = new AWSClient.Lambda()
Expand Down Expand Up @@ -195,7 +202,7 @@ describe("Integration Testing Event Bridge", () => {
};
await lambda.invoke(params).promise();

const eventBridgeEvents = await eventBridge.getEvents()
const eventBridgeEvents = await eventBridge.getLastEvent()
expect(eventBridgeEvents).toHaveEvent();
expect(eventBridgeEvents).toHaveEventWithSource("order.created");
});
Expand Down
33 changes: 31 additions & 2 deletions src/helpers/eventBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { PromiseResult } from "aws-sdk/lib/request";
import { AWSClient, region } from "./general";
import { removeUndefinedMessages } from "./utils/removeUndefinedMessages";

type EventBridgeMessage = { Body?: string };

type EventBridgeEvents = {
Messages: EventBridgeMessage[];
};

export default class EventBridge {
QueueUrl: string | undefined;
eventBridgeClient: AWSEventBridge | undefined;
Expand Down Expand Up @@ -129,12 +135,12 @@ export default class EventBridge {
})
.promise();

await this.getEvents(); // need to clear this manual published event from the SQS observer queue.
await this.getLastEvent(); // need to clear this manual published event from the SQS observer queue.

return result;
}

async getEvents(): Promise<SQS.ReceiveMessageResult | undefined> {
async getLastEvent(): Promise<SQS.ReceiveMessageResult | undefined> {
if (this.QueueUrl === undefined) {
throw new Error("QueueUrl is undefined");
}
Expand Down Expand Up @@ -169,6 +175,29 @@ export default class EventBridge {
return result;
}

async getAllEvents(): Promise<EventBridgeEvents> {
let allEventsFound = false;
// initialise allEventBridgeEvents at the start of the function
const allEventBridgeEvents: EventBridgeEvents = { Messages: [] };

while (!allEventsFound) {
try {
const lastEventBridgeEvent = await this.getLastEvent();

if (!lastEventBridgeEvent || !lastEventBridgeEvent.Messages) {
allEventsFound = true;
break;
}

allEventBridgeEvents.Messages.push(...lastEventBridgeEvent.Messages);
} catch (e) {
allEventsFound = true;
}
}

return allEventBridgeEvents;
}

async clear(): Promise<any> {
if (this.sqsClient === undefined) {
throw new Error(
Expand Down