Skip to main content
Version: 27.5

Using with DynamoDB

With the Global Setup/Teardown and Async Test Environment APIs, Jest can work smoothly with DynamoDB.

Use jest-dynamodb Preset

Jest DynamoDB provides all required configuration to run your tests using DynamoDB.

  1. First, install @shelf/jest-dynamodb
yarn add @shelf/jest-dynamodb --dev
  1. Specify preset in your Jest configuration:
{
"preset": "@shelf/jest-dynamodb"
}
  1. Create jest-dynamodb-config.js and define DynamoDB tables

See Create Table API

module.exports = {
tables: [
{
TableName: `files`,
KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}],
AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}],
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1},
},
// etc
],
};
  1. Configure DynamoDB client
const {DocumentClient} = require('aws-sdk/clients/dynamodb');

const isTest = process.env.JEST_WORKER_ID;
const config = {
convertEmptyValues: true,
...(isTest && {
endpoint: 'localhost:8000',
sslEnabled: false,
region: 'local-env',
}),
};

const ddb = new DocumentClient(config);
  1. Write tests
it('should insert item into table', async () => {
await ddb
.put({TableName: 'files', Item: {id: '1', hello: 'world'}})
.promise();

const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise();

expect(Item).toEqual({
id: '1',
hello: 'world',
});
});

There's no need to load any dependencies.

See documentation for details.