Installations
npm install @shelf/jest-dynamodb
Developer Guide
Typescript
No
Module System
N/A
Min. Node Version
>=16
Score
52.4
Supply Chain
92.1
Quality
83.9
Maintenance
50
Vulnerability
99.3
License
Releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (83.82%)
JavaScript (9.89%)
Shell (6.29%)
Developer
shelfio
Download Statistics
Total Downloads
5,461,308
Last Day
2,005
Last Week
21,789
Last Month
121,687
Last Year
1,470,020
GitHub Statistics
187 Stars
521 Commits
38 Forks
26 Watching
11 Branches
80 Contributors
Package Meta Information
Latest Version
3.5.0
Package Id
@shelf/jest-dynamodb@3.5.0
Unpacked Size
21.82 kB
Size
8.14 kB
File Count
28
Publised On
08 Aug 2024
Total Downloads
Cumulative downloads
Total Downloads
5,461,308
Last day
-59.1%
2,005
Compared to previous day
Last week
-14.7%
21,789
Compared to previous week
Last month
1.3%
121,687
Compared to previous month
Last year
6.7%
1,470,020
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
6
jest-dynamodb
Jest preset to run DynamoDB Local
Usage
0. Install
$ yarn add @shelf/jest-dynamodb --dev
Make sure java
runtime available for running DynamoDBLocal.jar
1. Create jest.config.js
1module.exports = { 2 preset: '@shelf/jest-dynamodb', 3};
2. Create jest-dynamodb-config.js
2.1 Properties
tables
- Type:
object[]
- Required:
true
Array of createTable params.
port
- Type:
number
- Required:
false
Port number. The default port number is 8000
.
hostname
- Type:
string
- Required:
false
Hostname. The default hostname is localhost
.
options
- Type:
string[]
- Required:
false
Additional arguments for dynamodb-local. The default value is ['-sharedDb']
.
clientConfig
- Type:
object
- Required:
false
Constructor params of DynamoDB client.
installerConfig
-
Type:
{installPath?: string, downloadUrl?: string}
-
Required:
false
-
installPath
defines the location where dynamodb-local is installed or will be installed. -
downloadUrl
defines the url of dynamodb-local package.
The default value is defined at https://github.com/rynop/dynamodb-local/blob/2e6c1cb2edde4de0dc51a71c193c510b939d4352/index.js#L16-L19
2.2 Examples
You can set up tables as an object:
Whole list of config properties can be found here
1/** 2 * @type {import('@shelf/jest-dynamodb/lib').Config}')} 3 */ 4const config = { 5 tables: [ 6 { 7 TableName: `files`, 8 KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}], 9 AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}], 10 ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}, 11 }, 12 // etc 13 ], 14 port: 8000, 15}; 16module.exports = config;
Or as an async function (particularly useful when resolving DynamoDB setup dynamically from serverless.yml
):
1module.exports = async () => { 2 const serverless = new (require('serverless'))(); 3 // If using monorepo where DynamoDB serverless.yml is in another directory 4 // const serverless = new (require('serverless'))({ servicePath: '../../../core/data' }); 5 6 await serverless.init(); 7 const service = await serverless.variables.populateService(); 8 const resources = service.resources.filter(r => Object.keys(r).includes('Resources'))[0]; 9 10 const tables = Object.keys(resources) 11 .map(name => resources[name]) 12 .filter(r => r.Type === 'AWS::DynamoDB::Table') 13 .map(r => r.Properties); 14 15 return { 16 tables, 17 port: 8000, 18 }; 19};
Or read table definitions from a CloudFormation template (example handles a !Sub on TableName, i.e. TableName: !Sub "${env}-users" ):
1const yaml = require('js-yaml'); 2const fs = require('fs'); 3const {CLOUDFORMATION_SCHEMA} = require('cloudformation-js-yaml-schema'); 4 5module.exports = async () => { 6 const cf = yaml.load(fs.readFileSync('../cf-templates/example-stack.yaml', 'utf8'), { 7 schema: CLOUDFORMATION_SCHEMA, 8 }); 9 var tables = []; 10 Object.keys(cf.Resources).forEach(item => { 11 tables.push(cf.Resources[item]); 12 }); 13 14 tables = tables 15 .filter(r => r.Type === 'AWS::DynamoDB::Table') 16 .map(r => { 17 let table = r.Properties; 18 if (typeof r.TableName === 'object') { 19 table.TableName = table.TableName.data.replace('${env}', 'test'); 20 } 21 delete table.TimeToLiveSpecification; //errors on dynamo-local 22 return table; 23 }); 24 25 return { 26 tables, 27 port: 8000, 28 }; 29};
3.1 Configure DynamoDB client (from aws-sdk v2)
1const {DocumentClient} = require('aws-sdk/clients/dynamodb'); 2 3const isTest = process.env.JEST_WORKER_ID; 4const config = { 5 convertEmptyValues: true, 6 ...(isTest && { 7 endpoint: 'localhost:8000', 8 sslEnabled: false, 9 region: 'local-env', 10 credentials: { 11 accessKeyId: 'fakeMyKeyId', 12 secretAccessKey: 'fakeSecretAccessKey', 13 }, 14 }), 15}; 16 17const ddb = new DocumentClient(config);
3.2 Configure DynamoDB client (from aws-sdk v3)
1const {DynamoDB} = require('@aws-sdk/client-dynamodb'); 2const {DynamoDBDocument} = require('@aws-sdk/lib-dynamodb'); 3 4const isTest = process.env.JEST_WORKER_ID; 5 6const ddb = DynamoDBDocument.from( 7 new DynamoDB({ 8 ...(isTest && { 9 endpoint: 'http://localhost:8000', 10 region: 'local-env', 11 credentials: { 12 accessKeyId: 'fakeMyKeyId', 13 secretAccessKey: 'fakeSecretAccessKey', 14 }, 15 }), 16 }), 17 { 18 marshallOptions: { 19 convertEmptyValues: true, 20 }, 21 } 22);
4. PROFIT! Write tests
1it('should insert item into table', async () => { 2 await ddb.put({TableName: 'files', Item: {id: '1', hello: 'world'}}).promise(); 3 4 const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise(); 5 6 expect(Item).toEqual({ 7 id: '1', 8 hello: 'world', 9 }); 10});
Monorepo Support
By default the jest-dynamodb-config.js
is read from cwd
directory, but this might not be suitable for monorepos with nested jest projects with nested jest.config.*
files nested in subdirectories.
If your jest-dynamodb-config.js
file is not located at {cwd}/jest-dynamodb-config.js
or you are using nested jest projects
, you can define the environment variable JEST_DYNAMODB_CONFIG
with the absolute path of the respective jest-dynamodb-config.js
file.
Example Using JEST_DYNAMODB_CONFIG
in nested project
// src/nested/project/jest.config.js
const path = require('path');
// Define path of project level config - extension not required as file will be imported via `require(process.env.JEST_DYNAMODB_CONFIG)`
process.env.JEST_DYNAMODB_CONFIG = path.resolve(__dirname, './jest-dynamodb-config');
module.exports = {
preset: '@shelf/jest-dynamodb'
displayName: 'nested-project',
};
Troubleshooting
UnknownError: Not Found
Perhaps something is using your port specified in jest-dynamodb-config.js
.
com.almworks.sqlite4java.Internal log WARNING: [sqlite] cannot open DB[1]:
See https://www.josephso.dev/using-jest-dynamodb-in-apple-silicon-platform-workaround/#community-build
Alternatives
- jest-dynalite - a much lighter version which spins up an instance for each runner & doesn't depend on Java
Read
Used by
See Also
Publish
1$ git checkout master 2$ yarn version 3$ yarn publish 4$ git push origin master --tags
License
MIT © Shelf
No vulnerabilities found.
Reason
15 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
0 existing vulnerabilities detected
Reason
license file detected
Details
- Info: project has a license file: license:0
- Info: FSF or OSI recognized license: MIT License: license:0
Reason
SAST tool is not run on all commits -- score normalized to 9
Details
- Warn: 28 commits out of 30 are checked with a SAST tool
Reason
Found 2/25 approved changesets -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Score
5.9
/10
Last Scanned on 2024-12-16
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