Gathering detailed insights and metrics for aws-sdk-mock
Gathering detailed insights and metrics for aws-sdk-mock
Gathering detailed insights and metrics for aws-sdk-mock
Gathering detailed insights and metrics for aws-sdk-mock
🌈 AWSomocks for Javascript/Node.js aws-sdk tested, documented & maintained. Contributions welcome!
npm install aws-sdk-mock
55
Supply Chain
96.5
Quality
86
Maintenance
100
Vulnerability
98.6
License
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
1,117 Stars
780 Commits
110 Forks
14 Watching
1 Branches
53 Contributors
Updated on 25 Nov 2024
Minified
Minified + Gzipped
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
-4.6%
50,922
Compared to previous day
Last week
2.8%
307,996
Compared to previous week
Last month
19.9%
1,278,115
Compared to previous month
Last year
-29.8%
14,342,872
Compared to previous year
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.
This library is best suited for AWS SDK for Javascript (v2)
- see the introductory post on the AWS blog for more context.
If you are using AWS SDK v3
you might not need this library, see:
aws-sdk-mock/issues#209
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
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.
Uses Sinon.js under the hood to mock the AWS SDK services and their associated methods.
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 |
aws-sdk-mock
from NPM1npm install aws-sdk-mock --save-dev
1 2const AWS = require('aws-sdk-mock'); 3 4AWS.mock('DynamoDB', 'putItem', function (params, callback){ 5 callback(null, 'successfully put item in database'); 6}); 7 8AWS.mock('SNS', 'publish', 'test-message'); 9 10// S3 getObject mock - return a Buffer object with file data 11AWS.mock('S3', 'getObject', Buffer.from(require('fs').readFileSync('testFile.csv'))); 12 13 14/** 15 TESTS 16**/ 17 18AWS.restore('SNS', 'publish'); 19AWS.restore('DynamoDB'); 20AWS.restore('S3'); 21// or AWS.restore(); this will restore all the methods and services
1import AWSMock from 'aws-sdk-mock'; 2import AWS from 'aws-sdk'; 3import { GetItemInput } from 'aws-sdk/clients/dynamodb'; 4 5beforeAll(async (done) => { 6 //get requires env vars 7 done(); 8 }); 9 10describe('the module', () => { 11 12/** 13 TESTS below here 14**/ 15 16 it('should mock getItem from DynamoDB', async () => { 17 // Overwriting DynamoDB.getItem() 18 AWSMock.setSDKInstance(AWS); 19 AWSMock.mock('DynamoDB', 'getItem', (params: GetItemInput, callback: Function) => { 20 console.log('DynamoDB', 'getItem', 'mock called'); 21 callback(null, {pk: 'foo', sk: 'bar'}); 22 }) 23 24 const input:GetItemInput = { TableName: '', Key: {} }; 25 const dynamodb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); 26 expect(await dynamodb.getItem(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); 27 28 AWSMock.restore('DynamoDB'); 29 }); 30 31 it('should mock reading from DocumentClient', async () => { 32 // Overwriting DynamoDB.DocumentClient.get() 33 AWSMock.setSDKInstance(AWS); 34 AWSMock.mock('DynamoDB.DocumentClient', 'get', (params: GetItemInput, callback: Function) => { 35 console.log('DynamoDB.DocumentClient', 'get', 'mock called'); 36 callback(null, {pk: 'foo', sk: 'bar'}); 37 }); 38 39 const input:GetItemInput = { TableName: '', Key: {} }; 40 const client = new AWS.DynamoDB.DocumentClient({apiVersion: '2012-08-10'}); 41 expect(await client.get(input).promise()).toStrictEqual({ pk: 'foo', sk: 'bar' }); 42 43 AWSMock.restore('DynamoDB.DocumentClient'); 44 }); 45});
You can also pass Sinon spies to the mock:
1const updateTableSpy = sinon.spy();
2AWS.mock('DynamoDB', 'updateTable', updateTableSpy);
3
4// Object under test
5myDynamoManager.scaleDownTable();
6
7// Assert on your Sinon spy as normal
8assert.isTrue(updateTableSpy.calledOnce, 'should update dynamo table via AWS SDK');
9const expectedParams = {
10 TableName: 'testTableName',
11 ProvisionedThroughput: {
12 ReadCapacityUnits: 1,
13 WriteCapacityUnits: 1
14 }
15};
16assert.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:
1const AWS = require('aws-sdk'); 2const sns = AWS.SNS(); 3const dynamoDb = AWS.DynamoDB(); 4 5exports.handler = function(event, context) { 6 // do something with the services e.g. sns.publish 7}
Example 2:
1const AWS = require('aws-sdk'); 2 3exports.handler = function(event, context) { 4 const sns = AWS.SNS(); 5 const dynamoDb = AWS.DynamoDB(); 6 // do something with the services e.g. sns.publish 7}
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):
1exports.handler = function(event, context) { 2 someAsyncFunction(() => { 3 const sns = AWS.SNS(); 4 const dynamoDb = AWS.DynamoDB(); 5 // do something with the services e.g. sns.publish 6 }); 7}
Example 2 (will work):
1exports.handler = function(event, context) { 2 const sns = AWS.SNS(); 3 const dynamoDb = AWS.DynamoDB(); 4 someAsyncFunction(() => { 5 // do something with the services e.g. sns.publish 6 }); 7}
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:
1AWS.mock('DynamoDB.DocumentClient', 'get', function(params, callback) { 2 callback(null, {Item: {Key: 'Value'}}); 3});
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:
1// OK 2AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); 3AWS.mock('DynamoDB', 'describeTable', 'message'); 4AWS.restore('DynamoDB'); 5AWS.restore('DynamoDB.DocumentClient'); 6 7// Not OK 8AWS.mock('DynamoDB', 'describeTable', 'message'); 9AWS.mock('DynamoDB.DocumentClient', 'get', 'message'); 10 11// Not OK 12AWS.restore('DynamoDB.DocumentClient'); 13AWS.restore('DynamoDB');
Some constructors of the aws-sdk will require you to pass through a configuration object.
1const csd = new AWS.CloudSearchDomain({
2 endpoint: 'your.end.point',
3 region: 'eu-west'
4});
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.
aws-sdk
module explicitlyProject 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:
1const path = require('path');
2const AWS = require('aws-sdk-mock');
3
4AWS.setSDK(path.resolve('../../functions/foo/node_modules/aws-sdk'));
5
6/**
7 TESTS
8**/
aws-sdk
object explicitlyDue 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:
1// test code 2const AWSMock = require('aws-sdk-mock'); 3import AWS from 'aws-sdk'; 4AWSMock.setSDKInstance(AWS); 5AWSMock.mock('SQS', /* ... */); 6 7// implementation code 8const sqs = new AWS.SQS();
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):
1const AWS = require('aws-sdk-mock'), 2 Q = require('q'); 3 4AWS.Promise = Q.Promise; 5 6 7/** 8 TESTS 9**/
Contributions welcome! Please submit issues or PRs if you think of anything that needs updating/improving
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
30 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
0 existing vulnerabilities detected
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More