Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Using with DynamoDB


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
Next: Using Jest with MongoDB and DynamoDB