Skip to main content
Version: 29.7

与 DynamoDB 一起使用

借助 全局设置/拆卸异步测试环境 API,Jest 可以与 动态数据库 顺利工作。

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

使用 jest-dynamodb 预设

¥Use jest-dynamodb Preset

Jest DynamoDB 提供使用 DynamoDB 运行测试所需的所有配置。

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

  1. 首先,安装 @shelf/jest-dynamodb

    ¥First, install @shelf/jest-dynamodb

npm install --save-dev @shelf/jest-dynamodb
  1. 在 Jest 配置中指定预设:

    ¥Specify preset in your Jest configuration:

{
"preset": "@shelf/jest-dynamodb"
}
  1. 创建 jest-dynamodb-config.js 并定义 DynamoDB 表

    ¥Create jest-dynamodb-config.js and define DynamoDB tables

创建表 API

¥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. 配置 DynamoDB 客户端

    ¥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.