• Stars
    star
    1,113
  • Rank 41,718 (Top 0.9 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created almost 9 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🌈 AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!

aws-sdk-mock

AWSome mocks for Javascript aws-sdk services.

Build Status codecov.io Dependency Status devDependency Status Known Vulnerabilities

This module was created to help test AWS Lambda functions but can be used in any situation where the AWS SDK needs to be mocked.

If you are new to Amazon WebServices Lambda (or need a refresher), please checkout our our
Beginners Guide to AWS Lambda: https://github.com/dwyl/learn-aws-lambda

Why?

Testing your code is essential everywhere you need reliability.

Using stubs means you can prevent a specific method from being called directly. In our case we want to prevent the actual AWS services to be called while testing functions that use the AWS SDK.

What?

Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods.

How? (Usage)

install aws-sdk-mock from NPM

npm install aws-sdk-mock --save-dev

Use in your Tests

Using plain JavaScript

const AWS = require('aws-sdk-mock');

AWS.mock('DynamoDB', 'putItem', function (params, callback){
  callback(null, 'successfully put item in database');
});

AWS.mock('SNS', 'publish', 'test-message');

// S3 getObject mock - return a Buffer object with file data
AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv')));


/**
    TESTS
**/

AWS.restore('SNS', 'publish');
AWS.restore('DynamoDB');
AWS.restore('S3');
// or AWS.restore(); this will restore all the methods and services

Using TypeScript

import AWSMock from 'aws-sdk-mock';
import AWS from 'aws-sdk';
import { GetItemInput } from 'aws-sdk/clients/dynamodb';

beforeAll(async (done) => {
  //get requires env vars
  done();
 });

describe('the module', () => {

/**
    TESTS below here
**/

  it('should mock getItem from DynamoDB', async () => {
    // Overwriting DynamoDB.getItem()
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => {
      console.log('DynamoDB', 'getItem', 'mock called');
      callback(null, {pk: 'foo', sk: 'bar'});
    })

    const input:GetItemInput = { TableName: '', Key: {} };
    const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'});
    expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });

    AWSMock.restore('DynamoDB');
  });

  it('should mock reading from DocumentClient', async () => {
    // Overwriting DynamoDB.DocumentClient.get()
    AWSMock.setSDKInstance(AWS);
    AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => {
      console.log('DynamoDB.DocumentClient', 'get', 'mock called');
      callback(null, {pk: 'foo', sk: 'bar'});
    });

    const input:GetItemInput = { TableName: '', Key: {} };
    const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'});
    expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' });

    AWSMock.restore('DynamoDB.DocumentClient');
  });
});

Sinon

You can also pass Sinon spies to the mock:

const updateTableSpy = sinon.spy();
AWS.mock('DynamoDB', 'updateTable', updateTableSpy);

// Object under test
myDynamoManager.scaleDownTable();

// Assert on your Sinon spy as normal
assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
const expectedParams = {
  TableName: 'testTableName',
  ProvisionedThroughput: {
    ReadCapacityUnits: 1,
    WriteCapacityUnits: 1
  }
};
assert.isTrue(updateTableSpy.calledWith(expectedParams), 'should pass correct parameters');

NB: The AWS Service needs to be initialised inside the function being tested in order for the SDK method to be mocked e.g for an AWS Lambda function example 1 will cause an error ConfigError: Missing region in config whereas in example 2 the sdk will be successfully mocked.

Example 1:

const AWS      = require('aws-sdk');
const sns      = AWS.SNS();
const dynamoDb = AWS.DynamoDB();

exports.handler = function(event, context) {
  // do something with the services e.g. sns.publish
}

Example 2:

const AWS = require('aws-sdk');

exports.handler = function(event, context) {
  const sns      = AWS.SNS();
  const dynamoDb = AWS.DynamoDB();
  // do something with the services e.g. sns.publish
}

Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either.

Example 1 (won't work):

exports.handler = function(event, context) {
  someAsyncFunction(() => {
    const sns      = AWS.SNS();
    const dynamoDb = AWS.DynamoDB();
    // do something with the services e.g. sns.publish
  });
}

Example 2 (will work):

exports.handler = function(event, context) {
  const sns      = AWS.SNS();
  const dynamoDb = AWS.DynamoDB();
  someAsyncFunction(() => {
    // do something with the services e.g. sns.publish
  });
}

Nested services

It is possible to mock nested services like DynamoDB.DocumentClient. Simply use this dot-notation name as the service parameter to the mock() and restore() methods:

AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) {
  callback(null, {Item: {Key: 'Value'}});
});

NB: Use caution when mocking both a nested service and its parent service. The nested service should be mocked before and restored after its parent:

// OK
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.restore('DynamoDB');
AWS.restore('DynamoDB.DocumentClient');

// Not OK
AWS.mock('DynamoDB', 'describeTable', 'message');
AWS.mock('DynamoDB.DocumentClient', 'get', 'message');

// Not OK
AWS.restore('DynamoDB.DocumentClient');
AWS.restore('DynamoDB');

Don't worry about the constructor configuration

Some constructors of the aws-sdk will require you to pass through a configuration object.

const csd = new AWS.CloudSearchDomain({
  endpoint: 'your.end.point',
  region: 'eu-west'
});

Most mocking solutions with throw an InvalidEndpoint: AWS.CloudSearchDomain requires an explicit 'endpoint' configuration option when you try to mock this.

aws-sdk-mock will take care of this during mock creation so you won't get any configuration errors!
If configurations errors still occur it means you passed wrong configuration in your implementation.

Setting the aws-sdk module explicitly

Project structures that don't include the aws-sdk at the top level node_modules project folder will not be properly mocked. An example of this would be installing the aws-sdk in a nested project directory. You can get around this by explicitly setting the path to a nested aws-sdk module using setSDK().

Example:

const path = require('path');
const AWS = require('aws-sdk-mock');

AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));

/**
    TESTS
**/

Setting the aws-sdk object explicitly

Due to transpiling, code written in TypeScript or ES6 may not correctly mock because the aws-sdk object created within aws-sdk-mock will not be equal to the object created within the code to test. In addition, it is sometimes convenient to have multiple SDK instances in a test. For either scenario, it is possible to pass in the SDK object directly using setSDKInstance().

Example:

// test code
const AWSMock = require('aws-sdk-mock');
import AWS from 'aws-sdk';
AWSMock.setSDKInstance(AWS);
AWSMock.mock('SQS', /* ... */);

// implementation code
const sqs = new AWS.SQS();

Configuring promises

If your environment lacks a global Promise constructor (e.g. nodejs 0.10), you can explicitly set the promises on aws-sdk-mock. Set the value of AWS.Promise to the constructor for your chosen promise library.

Example (if Q is your promise library of choice):

const AWS = require('aws-sdk-mock'),
    Q = require('q');

AWS.Promise = Q.Promise;


/**
    TESTS
**/

Documentation

AWS.mock(service, method, replace)

Replaces a method on an AWS service with a replacement function or string.

Param Type Optional/Required Description
service string Required AWS service to mock e.g. SNS, DynamoDB, S3
method string Required method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB'
replace string or function Required A string or function to replace the method

AWS.restore(service, method)

Removes the mock to restore the specified AWS service

Param Type Optional/Required Description
service string Optional AWS service to restore - If only the service is specified, all the methods are restored
method string Optional Method on AWS service to restore

If AWS.restore is called without arguments (AWS.restore()) then all the services and their associated methods are restored i.e. equivalent to a 'restore all' function.

AWS.remock(service, method, replace)

Updates the replace method on an existing mocked service.

Param Type Optional/Required Description
service string Required AWS service to mock e.g. SNS, DynamoDB, S3
method string Required method on AWS service to mock e.g. 'publish' (for SNS), 'putItem' for 'DynamoDB'
replace string or function Required A string or function to replace the method

AWS.setSDK(path)

Explicitly set the require path for the aws-sdk

Param Type Optional/Required Description
path string Required Path to a nested AWS SDK node module

AWS.setSDKInstance(sdk)

Explicitly set the aws-sdk instance to use

Param Type Optional/Required Description
sdk object Required The AWS SDK object

Background Reading

Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving

More Repositories

1

english-words

πŸ“ A text file containing 479k English words for all your dictionary/word-based projects e.g: auto-completion / autosuggestion
Python
9,337
star
2

learn-json-web-tokens

πŸ” Learn how to use JSON Web Token (JWT) to secure your next Web App! (Tutorial/Example with Tests!!)
JavaScript
4,178
star
3

learn-to-send-email-via-google-script-html-no-server

πŸ“§ An Example of using an HTML form (e.g: "Contact Us" on a website) to send Email without a Backend Server (using a Google Script) perfect for static websites that need to collect data.
HTML
3,140
star
4

repo-badges

⭐ Use repo badges (build passing, coverage, etc) in your readme/markdown file to signal code quality in a project.
HTML
2,831
star
5

learn-tdd

βœ… A brief introduction to Test Driven Development (TDD) in JavaScript (Complete Beginner's Step-by-Step Tutorial)
JavaScript
2,698
star
6

start-here

πŸ’‘ A Quick-start Guide for People who want to dwyl ❀️ βœ…
1,734
star
7

learn-elixir

πŸ’§ Learn the Elixir programming language to build functional, fast, scalable and maintainable web applications!
Elixir
1,611
star
8

learn-travis

😎 A quick Travis CI (Continuous Integration) Tutorial for Node.js developers
JavaScript
1,251
star
9

Javascript-the-Good-Parts-notes

πŸ“– Notes on the seminal "JavaScript the Good Parts: by Douglas Crockford
1,193
star
10

learn-aws-lambda

✨ Learn how to use AWS Lambda to easily create infinitely scalable web services
JavaScript
1,035
star
11

book

πŸ“— Our Book on Full-Stack Web Application Development covering User Experience (UX) Design, Mobile/Offline/Security First, Progressive Enhancement, Continuous Integration/Deployment, Testing (UX/TDD/BDD), Performance-Driven-Development and much more!
Rust
818
star
12

hapi-auth-jwt2

πŸ”’ Secure Hapi.js authentication plugin using JSON Web Tokens (JWT) in Headers, URL or Cookies
JavaScript
795
star
13

learn-hapi

β˜€οΈ Learn to use Hapi.js (Node.js) web framework to build scalable apps in less time
HTML
794
star
14

phoenix-chat-example

πŸ’¬ The Step-by-Step Beginners Tutorial for Building, Testing & Deploying a Chat app in Phoenix 1.7 [Latest] πŸš€
Elixir
760
star
15

learn-tachyons

😍 Learn how to use Tachyons to craft beautiful, responsive and fast UI with functional CSS!
HTML
673
star
16

learn-phoenix-framework

πŸ”₯ Phoenix is the web framework without compromise on speed, reliability or maintainability! Don't settle for less. πŸš€
Elixir
650
star
17

javascript-todo-list-tutorial

βœ… A step-by-step complete beginner example/tutorial for building a Todo List App (TodoMVC) from scratch in JavaScript following Test Driven Development (TDD) best practice. 🌱
JavaScript
623
star
18

learn-nightwatch

🌜 Learn how to use Nightwatch.js to easily & automatically test your web apps in *real* web browsers.
JavaScript
585
star
19

learn-elm

🌈 discover the beautiful programming language that makes front-end web apps a joy to build and maintain!
HTML
483
star
20

learn-redux

πŸ’₯ Comprehensive Notes for Learning (how to use) Redux to manage state in your Web/Mobile (React.js) Apps.
HTML
446
star
21

hits

πŸ“ˆ General purpose hits (page views) counter
Elixir
432
star
22

learn-devops

🚧 Learn the craft of "DevOps" (Developer Operations) to Deploy your App and Monitor it so it stays "Up"!
Shell
413
star
23

phoenix-liveview-counter-tutorial

🀯 beginners tutorial building a real time counter in Phoenix 1.7.14 + LiveView 1.0 ⚑️ Learn the fundamentals from first principals so you can make something amazing! πŸš€
Elixir
374
star
24

hapi-socketio-redis-chat-example

πŸ’¬ Real-time Chat using Hapi.js + Socket.io + Redis Pub/Sub (example with tests!!)
Elm
366
star
25

hapi-typescript-example

⚑ Hapi.Js + Typescript = Awesomeness
TypeScript
351
star
26

learn-istanbul

🏁 Learn how to use the Istanbul JavaScript Code Coverage Tool
JavaScript
339
star
27

learn-redis

πŸ“• Need to store/access your data as fast as possible? Learn Redis! Beginners Tutorial using Node.js πŸš€
JavaScript
291
star
28

technology-stack

πŸš€ Detailed description + diagram of the Open Source Technology Stack we use for dwyl projects.
JavaScript
288
star
29

phoenix-ecto-encryption-example

πŸ” A detailed example for how to encrypt data in an Elixir (Phoenix v1.7) App before inserting into a database using Ecto Types
Elixir
274
star
30

learn-elasticsearch

πŸ” Learn how to use ElasticSearch to power a great search experience for your project/product/website.
Elixir
265
star
31

elixir-auth-google

πŸ‘€Minimalist Google OAuth Authentication for Elixir Apps. Tested, Documented & Maintained. Setup in 5 mins. πŸš€
Elixir
263
star
32

home

🏑 πŸ‘©β€πŸ’» πŸ’‘ home is where you can [learn to] build the future surrounded by like-minded creative, friendly and [intrinsically] motivated people focussed on health, fitness and making things people and the world need!
246
star
33

learn-docker

🚒 Learn how to use docker.io containers to consistently deploy your apps on any infrastructure.
Dockerfile
220
star
34

learn-elm-architecture-in-javascript

πŸ¦„ Learn how to build web apps using the Elm Architecture in "vanilla" JavaScript (step-by-step TDD tutorial)!
JavaScript
211
star
35

learn-environment-variables

πŸ“Learn how to use Environment Variables to keep your passwords and API keys secret. πŸ”
JavaScript
201
star
36

learn-postgresql

🐘 Learn how to use PostgreSQL and Structured Query Language (SQL) to store and query your relational data. πŸ”
JavaScript
195
star
37

learn-tape

βœ… Learn how to use Tape for JavaScript/Node.js Test Driven Development (TDD) - Ten-Minute Testing Tutorial
JavaScript
187
star
38

sendemail

πŸ’Œ Simplifies reliably sending emails from your node.js apps using AWS Simple Email Service (SES)
JavaScript
181
star
39

phoenix-todo-list-tutorial

βœ… Complete beginners tutorial building a todo list from scratch in Phoenix 1.7 (latest)
Elixir
171
star
40

quotes

πŸ’¬ a curated list of quotes that inspire action + code that returns quotes by tag/author/etc. πŸ’‘
Elixir
163
star
41

learn-heroku

🏁 Learn how to deploy your web application to Heroku from scratch step-by-step in 7 minutes!
Python
153
star
42

decache

:shipit: Delete Cached node_modules useful when you need to "un-require" during testing for a fresh state.
JavaScript
151
star
43

learn-chrome-extensions

🌐 Discover how to build and deploy a Google Chrome Extension for your Project!
139
star
44

labels

🏷 Sync GitHub Labels from any Source to Target Repositories for Consistency across all your projects!
Elixir
138
star
45

learn-ab-and-multivariate-testing

πŸ†Ž Tutorial on A/B and multivariate testing βœ”οΈ
137
star
46

ISO-27001-2013-information-technology-security

πŸ” Probably the most boring-but-necessary repo on GitHub. If you care about the security/privacy of your data...! βœ…
136
star
47

auth

πŸšͺ πŸ” UX-focussed Turnkey Authentication Solution for Web Apps/APIs (Documented, Tested & Maintained)
Elixir
135
star
48

web-form-to-google-sheet

A simple example of sending data from an ordinary web form straight to a Google Spreadsheet without a server.
HTML
133
star
49

app

Clear your mind. Organise your life. Ignore distractions. Focus on what matters.
Dart
133
star
50

phoenix-liveview-chat-example

πŸ’¬ Step-by-step tutorial creates a Chat App using Phoenix LiveView including Presence, Authentication and Style with Tailwind CSS
Elixir
130
star
51

learn-circleci

βœ… A quick intro to Circle CI (Continuous Integration) for JavaScript developers.
121
star
52

learn-regex

⁉️ A simple REGular EXpression tutorial in JavaScript
120
star
53

learn-react

"The possibilities are numerous once we decide to act and not react." ~ George Bernard Shaw
HTML
108
star
54

learn-aws-iot

πŸ’‘ Learn how to use Amazon Web Services Internet of Things (IoT) service to build connected applications.
JavaScript
101
star
55

env2

πŸ’» Simple environment variable (from config file) loader for your node.js app
JavaScript
100
star
56

how-to-choose-a-database

How to choose the right dabase
97
star
57

flutter-todo-list-tutorial

βœ… A detailed example/tutorial building a cross-platform Todo List App using Flutter πŸ¦‹
Dart
91
star
58

imgup

πŸŒ… Effortless image uploads to AWS S3 with automatic resizing including REST API.
Elixir
88
star
59

mvp

πŸ“² simplest version of the @dwyl app
Elixir
87
star
60

contributing

πŸ“‹ Guidelines & Workflow for people contributing to our project(s) on GitHub. Please ⭐ to confirm you've read & understood! βœ…
86
star
61

learn-flutter

πŸ¦‹ Learn how to use Flutter to Build Cross-platform Native Mobile Apps
JavaScript
86
star
62

javascript-best-practice

A collection of JavaScript Best Practices
83
star
63

learn-amazon-web-services

⭐ Amazing Guide to using Amazon Web Services (AWS)! ☁️
83
star
64

range-touch

πŸ“± Use HTML5 range input on touch devices (iPhone, iPad & Android) without bloatware!
JavaScript
83
star
65

learn-pre-commit

βœ… Pre-commit hooks let you run checks before allowing a commit (e.g. JSLint or check Test Coverage).
JavaScript
80
star
66

product-owner-guide

πŸš€ A rough guide for people working with dwyl as Product Owners
78
star
67

phoenix-ecto-append-only-log-example

πŸ“ A step-by-step example/tutorial showing how to build a Phoenix (Elixir) App where all data is immutable (append only). Precursor to Blockchain, IPFS or Solid!
Elixir
78
star
68

fields

🌻 fields is a collection of useful field definitions (Custom Ecto Types) that helps you easily define an Ecto Schema with validation, encryption and hashing functions so that you can ship your Elixir/Phoenix App much faster!
Elixir
77
star
69

goodparts

πŸ™ˆ An ESLint Style that only allows JavaScript the Good Parts (and "Better Parts") in your code.
JavaScript
77
star
70

hapi-error

β˜” Intercept errors in your Hapi Web App/API and send a *useful* message to the client OR redirect to the desired endpoint.
JavaScript
76
star
71

process-handbook

πŸ“— Contains our processes, questions and journey to creating a team
HTML
76
star
72

terminate

♻️ Terminate a Node.js Process (and all Child Processes) based on the Process ID
JavaScript
76
star
73

aws-lambda-deploy

☁️ πŸš€ Effortlessly deploy Amazon Web Services Lambda function(s) with a single command. Less to configure. Latest AWS SDK and Node.js v20!
JavaScript
74
star
74

dev-setup

✈️ A quick-start guide for new engineers on how to set up their Dev environment
73
star
75

hapi-login-example-postgres

🐰 A simple registration + login form example using hapi-register, hapi-login & hapi-auth-jwt2 with a PostgreSQL DB
JavaScript
69
star
76

flutter-bloc-tutorial

A step-by-step example/tutorial explaining the benefits of the BLoC architecture and bloc library including tests!
Dart
67
star
77

phoenix-liveview-todo-list-tutorial

βœ… Beginners tutorial building a Realtime Todo List in Phoenix 1.6.10 + LiveView 0.17.10 ⚑️ Feedback very welcome!
Elixir
65
star
78

learn-security

πŸ” For most technology projects Security is an "after thought", it does not have to be that way; let's be proactive!
64
star
79

learn-javascript

A Series of Simple Steps in JavaScript :-)
HTML
63
star
80

chat

πŸ’¬ Probably the fastest, most reliable/scalable chat system on the internet.
Elixir
62
star
81

learn-jsdoc

πŸ“˜ Use JSDoc and a few carefully crafted comments to document your JavaScript code!
CSS
60
star
82

ampl

πŸ“± ⚑ Ampl transforms Markdown into AMP-compliant html so it loads super-fast!
JavaScript
58
star
83

aguid

❄️ A Globally Unique IDentifier (GUID) generator in JS. (deterministic or random - you chose!)
JavaScript
57
star
84

tudo

βœ… Want to see where you could help on an open dwyl issue?
Elixir
57
star
85

learn-apple-watch-development

πŸ“— Learn how to build Native Apple Watch (+iPhone) apps from scratch!
Swift
55
star
86

learn-qunit

βœ… A quick introduction to JavaScript unit testing with QUnit
JavaScript
51
star
87

learn-ngrok

☁️ Learn how to use ngrok to share access to a Web App/Site running on your "localhost" with the world!
HTML
50
star
88

learn-jshint

πŸ’© Learn how to use the ~~jshint~~ code quality/consistency tool.
JavaScript
49
star
89

hapi-auth-jwt2-example

πŸ”’ A functional example Hapi.js app using hapi-auth-jwt2 & Redis (hosted on Heroku) with tests!
JavaScript
49
star
90

tachyons-bootstrap

πŸ‘’Bootstrap recreated using tachyons functional css
HTML
48
star
91

learn-tailwind

🌬️ Learn Tailwind CSS to craft pixel-perfect web apps/sites in less time! 😍
Elixir
48
star
92

esta

πŸ” Simple + Fast ElasticSearch Node.js client. Beginner-friendly defaults & Heroku support βœ… πŸš€
JavaScript
48
star
93

learn-node-js-by-example

☁️ Practical node.js examples.
HTML
47
star
94

elixir-pre-commit

βœ… Pre-commit hooks for Elixir projects
Elixir
46
star
95

product-roadmap

🌐 Because why wouldn't you make your company's product roadmap Public on GitHub?
46
star
96

redis-connection

⚑ Single Redis Connection that can be used anywhere in your node.js app and closed once (e.g in tests)
JavaScript
45
star
97

learn-graphQL

❓Learn to use GraphQL - A query language that allows client applications to specify their data fetching requirements
JavaScript
45
star
98

aws-lambda-test-utils

Mock event and context objects without fluff.
JavaScript
44
star
99

hapi-login

πŸšͺ The Simplest Possible (Email + Password) Login for Hapi.js Apps βœ…
JavaScript
43
star
100

learn-riot

🐎 Riot.js lets you build apps that are simpler and load/run faster than any other JS framework/library.
HTML
43
star