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
  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @shelf/jest-dynamodb
  1. yarn add --dev @shelf/jest-dynamodb
  1. pnpm add --save-dev @shelf/jest-dynamodb
  1. Specify preset in your Jest configuration:
  1. {
  2. "preset": "@shelf/jest-dynamodb"
  3. }
  1. Create jest-dynamodb-config.js and define DynamoDB tables

See Create Table API

  1. module.exports = {
  2. tables: [
  3. {
  4. TableName: `files`,
  5. KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}],
  6. AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}],
  7. ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1},
  8. },
  9. // etc
  10. ],
  11. };
  1. Configure DynamoDB client
  1. const {DocumentClient} = require('aws-sdk/clients/dynamodb');
  2. const isTest = process.env.JEST_WORKER_ID;
  3. const config = {
  4. convertEmptyValues: true,
  5. ...(isTest && {
  6. endpoint: 'localhost:8000',
  7. sslEnabled: false,
  8. region: 'local-env',
  9. }),
  10. };
  11. const ddb = new DocumentClient(config);
  1. Write tests
  1. it('should insert item into table', async () => {
  2. await ddb
  3. .put({TableName: 'files', Item: {id: '1', hello: 'world'}})
  4. .promise();
  5. const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise();
  6. expect(Item).toEqual({
  7. id: '1',
  8. hello: 'world',
  9. });
  10. });

无需加载任何依赖项。

See documentation for details.