Using Jest with DynamoDB: Configuration and Testing Guide
By using the Global Setup/Teardown and Async Test Environment APIs, Jest will work smoothly with DynamoDB.
Use jest-dynamodb Preset
Jest DynamoDB will provide all required configuration to run your tests using DynamoDB.
We will walk you through the steps required to run a Jest test on a DynamoDB
1. First you need to install @shelf/jest-dynamodb
yarn add @shelf/jest-dynamodb -dev
2. Then you should specify preset in your Jest configuration:
{
"preset": "@shelf/jest-dynamodb"
}
3. Next thing you need to do is to create jest-dynamodb-config.js and define the DynamoDB tables
module.exports = {
tables: [
{
TableName: `files`,
KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}],
AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}],
ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1},
},
// etc
],
};
4. After that, you should 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);
5. Finally, you can then 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',
});
});
Let us run an example that encompasses both the configuration and the test itself:
//require dynamodb library
const {DocumentClient} = require('aws-sdk/clients/dynamodb');
const isTest = process.env.JEST_WORKER_ID;
//set your configurations
const config = {
convertEmptyValues: true,
...(isTest && {
endpoint: 'localhost:8000',
sslEnabled: false,
region: 'local-env',
}),
};
//creates an instance of the config set above
const ddb = new DocumentClient(config);
//now write a mock
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',
});
});
Just like in the test using MongoDB there is no need to load any dependencies.
Previous:
Bypassing Module Mocks in Jest: Accessing Original Implementations.
Next:
Configuring Jest with MongoDB: A Step-by-Step Guide.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/jest/using-with-dynamodb.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics