跳至主要內容
版本: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 資料表

請參閱 建立資料表 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',
});
});

無需載入任何相依性。

查看 文件 以取得詳細資訊。