๐Ÿฅพ A simple way to do testing AWS Services and Jest or Serverless and Jest

Overview

jest-localstack-preset

ci

Install

Install via yarn or npm

$ yarn add https://github.com/thadeu/jest-localstack-preset.git

or

$ npm i https://github.com/thadeu/jest-localstack-preset.git

Dependencies

Configuration

Configure jest.config.js, adding a custom preset

module.exports = {
  preset: '@thadeu/jest-localstack-preset',
  ...
}

Create jest-localstack-preset file, for example.

module.exports = {
  services: ['dynamodb', 'kinesis', 's3', 'apigateway', 'lambda'],
  showLog: false,
  readyTimeout: 10000,
  S3Buckets: [
    {
      Bucket: 'examplebucket',
    },
  ],
  DynamoDB: [
    {
      TableName: `users_test`,
      BillingMode: 'PAY_PER_REQUEST',
      KeySchema: [
        { AttributeName: 'pk', KeyType: 'HASH' },
        { AttributeName: 'sk', KeyType: 'RANGE' },
      ],
      AttributeDefinitions: [
        { AttributeName: 'pk', AttributeType: 'S' },
        { AttributeName: 'sk', AttributeType: 'S' },
      ],
    },
  ],
}

Usage

Use custom endpoint process.env.AWS_ENDPOINT_URL for general or specific to DynamoDB process.env.AWS_DYNAMODB_ENDPOINT_URL in the AWS clients in your code., for example:

const AWS = require('aws-sdk')

const Table = new AWS.DynamoDB.DocumentClient({
  endpoint: process.env.AWS_DYNAMODB_ENDPOINT_URL,
})

So, create your tests using Jest.

An example for DynamoDB.

const AWS = require('aws-sdk')

const Table = new AWS.DynamoDB.DocumentClient({
  endpoint: process.env.AWS_DYNAMODB_ENDPOINT_URL,
})

it('should insert item into table', async () => {
  await Table.put({
    TableName: 'users_test',
    Item: { pk: '1', sk: 'jest-localstack-preset' },
  }).promise()

  const { Count } = await Table.scan({ TableName: 'users_test' }).promise()
  expect(Count).toBe(1)
})

An example for S3

const AWS = require('aws-sdk')

const s3 = new AWS.S3({
  endpoint: process.env.AWS_ENDPOINT_URL,
  s3ForcePathStyle: true,
})

it('must be create a bucket', async () => {
  await s3.createBucket({ Bucket: 'examplebucket' }).promise()

  const { Buckets } = await s3.listBuckets().promise()

  expect(Buckets.length).toBe(1)
  expect(Buckets[0].Name).toBe('examplebucket')
})

Usually you go to use other files, class and functions.

// UserReposity.js
const AWS = require('aws-sdk')

const Table = new AWS.DynamoDB.DocumentClient({
  endpoint: process.env.AWS_DYNAMODB_ENDPOINT_URL,
  region: process.env.AWS_REGION,
})

export default class UserReposity {
  static async all(props = {}) {
    return Table.scan({ TableName: 'users', ...props }).promise()
  }

  static async save(props) {
    return Table.put({
      TableName: 'users',
      ...props,
    }).promise()
  }
}

// UserReposity.test.js
import UserReposity from './UserReposity'

describe('UserReposity', function() {
  it('should insert item into repository', async () => {
    await UserReposity.save({
      Item: { pk: '1', sk: 'jest-localstack-preset' },
    })

    const { Count } = await UserReposity.all()
    expect(Count).toBe(1)
  })
})

In this moment, all process will be make using LocalStack.

How Its Works?

Programmatically, we start a docker container with localstack, we run all tests and then, when tests finished, we destroy all containers related

What services work?

Basically, whatever!

For more AWS Service available visit, https://docs.localstack.cloud/aws/feature-coverage/

Debugging

You can enabled debug flag using your custom environment.

Package LocalStack
DEBUG=jest-localstack-preset LOCALSTACK_DEBUG=[false

CI (Continuous Integration)

Simple example

name: ci

on: push

jobs:
  jest:
    name: jest
    runs-on: ubuntu-latest

    services:
      localstack:
        image: localstack/localstack

    defaults:
      run:
        working-directory: ./

    steps:
      - uses: actions/checkout@v2

      - uses: actions/cache@v2
        with:
          path: '**/node_modules'
          key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-modules-

      - name: Setup NodeJS
        uses: actions/setup-node@v2
        with:
          node-version: 14.17.x

      - name: Install Yarn Dependencies
        run: yarn install --frozen-lockfile

      - name: Yarn Jest
        run: yarn test
        env:
          LOCALSTACK_DEBUG: true

Disclaimer

This project is based on the amazing project https://github.com/goldsam/jest-localstack.

Contributing

Once you've made your great commits (include tests, please):

  1. Fork this repository
  2. Create a topic branch - git checkout -b my_branch
  3. Push to your branch - git push origin my_branch
  4. Create a pull request
  5. That's it!

Please respect the indentation rules and code style. And use 2 spaces, not tabs. And don't touch the version thing or distribution files; this will be made when a new version is going to be release

License

The Dockerfile and associated scripts and documentation in this project are released under the MIT License.

You might also like...

Catalogist is the easy way to catalog and make your software and (micro)services visible to your organization in a lightweight and developer-friendly way.

Catalogist is the easy way to catalog and make your software and (micro)services visible to your organization in a lightweight and developer-friendly way.

catalogist ๐Ÿ“š ๐Ÿ““ ๐Ÿ“’ ๐Ÿ“– ๐Ÿ”– The easy way to catalog and make your software and (micro)services visible to your organization through an API You were a pe

Dec 13, 2022

Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services.

SlaMax Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services. Here are a few use-cases y

Sep 19, 2022

This repository demonstrates how to integrate your Dialogflow agent with 3rd-party services services using a Node.JS backend service

This repository demonstrates how to integrate your Dialogflow agent with 3rd-party services services using a Node.JS backend service

This repository demonstrates how to integrate your Dialogflow agent with 3rd-party services services using a Node.JS backend service. Integrating your service allows you to take actions based on end-user expressions and send dynamic responses back to the end-user.

Jul 21, 2022

A Serverless GraphQL Sample project using Apollo and Serverless Framework with TypeScript and Webpack.

Serverless GraphQL Boilerplate This is a base project with a structure that includes Serverless Framework, Apollo, TypeScript and Webpack. It can be d

Aug 23, 2022

Get-A-Room example application using Domain Driven Design and Clean Architecture. Written in TypeScript and deployed to AWS with a serverless stack.

Get-A-Room example application using Domain Driven Design and Clean Architecture. Written in TypeScript and deployed to AWS with a serverless stack.

Domain Driven Microservices on AWS in Practice This project provides a Domain Driven Design & Clean Architecture-informed, multi-service event-driven

Dec 31, 2022

An affordable and easy-to-use monitoring tool for your AWS serverless applications.

An affordable and easy-to-use monitoring tool for your AWS serverless applications.

AWS Serverless Applications Monitoring Tool Table of Contents Motivation for Project Getting Started AWS End Users Installation and Setup Lambda Metri

Sep 21, 2022

๐Ÿš€ Using top-level await in AWS Lambda with TypeScript, esbuild and Serverless Framework

๐Ÿš€ Using top-level await in AWS Lambda with TypeScript, esbuild and Serverless Framework

๐Ÿš€ Top-level await in AWS Lamba with TypeScript Articles https://dev.to/oieduardorabelo/top-level-await-in-aws-lamba-with-typescript-1bf0 https://medi

Nov 23, 2022

An AWS Cloud Native application using CDK that defines a Serverless Event Driven application for interacting with Twitter and utilising Machine Learning / AI as a Service.

An AWS Cloud Native application using CDK that defines a Serverless Event Driven application for interacting with Twitter and utilising Machine Learning / AI as a Service.

AWS Serverless Event Driven Twitter Bot An AWS Cloud Native application using CDK (Written in TypeScript) that defines a Serverless Event Driven appli

Dec 18, 2022

A technology stack solution using the AWS Serverless architecture.Atlas stack for building applications focused on generating value.

Atlas A technology stack solution using the AWS Serverless architecture.Atlas stack for building applications focused on generating value. Description

Dec 15, 2022
Comments
Releases(v1.0.10)
Owner
thadeu
Ruby and JavaScript coder. #borntocode
thadeu
AWS Lambda & Serverless - Developer Guide with Hands-on Labs. Develop thousands line of aws lambda functions interact to aws serverless services with real-world hands-on labs

AWS Lambda & Serverless - Developer Guide with Hands-on Labs UDEMY COURSE WITH DISCOUNTED - Step by Step Development of this Repository -> https://www

awsrun 35 Dec 17, 2022
Learn Web 2.0 and Web 3.0 Development using Next.js, Typescript, AWS CDK, AWS Serverless, Ethereum and AWS Aurora Serverless

Learn Web 2.0 Cloud and Web 3.0 Development in Baby Steps In this course repo we will learn Web 2.0 cloud development using the latest state of the ar

Panacloud Multi-Cloud Internet-Scale Modern Global Apps 89 Jan 3, 2023
Under the Sea is an official AWS workshop delivered by AWS SAs and AWS Partners to help customers and partners to learn about AIOps with serverless architectures on AWS.

Under the Sea - AIOps with Serverless Workshop Under the Sea is an exciting MMORPG developed by the famous entrepreneur behind Wild Rydes, the most po

AWS Samples 4 Nov 16, 2022
a stack-separated way to bringing together common AWS services useful in a fullstack application that uses AWS Amplify libraries

Fullstack CDK Helpers This project helps developers create common AWS services that are useful in creating fullstack applications. Backend services ar

Focus Otter 14 Nov 26, 2022
Smart Territory Framework Core using NEC Scorpio 2.0 and AWS serverless services

Smart Territory Framework Core - STF Core using NEC Scorpio Broker โš ๏ธ This stack is for demonstration purposes only. The nested stack deploying the NE

AWS Samples 9 Sep 30, 2022
A serverless AWS expense tracker API. AWS Lambda functions, API gateway, and Dynamodb are among the ingredients.

AWS-Serverless-API A serverless AWS expense tracker API. AWS Lambda functions API gateway Dynamodb Endpoints Create a new expense: Method: POST Body f

Ondiek Elijah Ochieng 1 Jul 16, 2022
MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are still part of a flow in the AWS cloud remote.

MerLoc MerLoc is a live AWS Lambda function development and debugging tool. MerLoc allows you to run AWS Lambda functions on your local while they are

Thundra 165 Dec 21, 2022
Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK

serverless dynamodb integration tests ?? Example Serverless DynamoDB integration tests using Jest, TypeScript and the AWS CDK Introduction How to inte

Lee Gilmore 8 Nov 4, 2022
A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Prisma ORM. Deploys to Fly.io

Live Demo ยท Twitter A testing focused Remix Stack, that integrates E2E & Unit testing with Playwright, Vitest, MSW and Testing Library. Driven by Pris

Remix Stacks 18 Oct 31, 2022