メインコンテンツへスキップ
バージョン: 29.7

DynamoDBとの使用

グローバルセットアップ/ティアダウン非同期テスト環境APIを使用することで、JestはDynamoDBとスムーズに連携できます。

jest-dynamodbプリセットを使用する

Jest DynamoDBは、DynamoDBを使用してテストを実行するために必要なすべての構成を提供します。

  1. まず、@shelf/jest-dynamodbをインストールします
npm install --save-dev @shelf/jest-dynamodb
  1. Jest構成でプリセットを指定します
{
"preset": "@shelf/jest-dynamodb"
}
  1. jest-dynamodb-config.jsを作成し、DynamoDBテーブルを定義します

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クライアントを構成します
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. テストを記述します
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',
});
});

依存関係をロードする必要はありません。

詳細についてはドキュメントを参照してください。