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

DynamoDB の使用

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

Global Setup/Teardown および Async Test Environment 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',
});
});

依存関係を追加で読み込む必要はありません。

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