|
| 1 | +--- |
| 2 | +id: dynamodb |
| 3 | +title: Using with DynamoDB |
| 4 | +--- |
| 5 | + |
| 6 | +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [DynamoDB](https://aws.amazon.com/dynamodb/). |
| 7 | + |
| 8 | +## Use jest-dynamodb Preset |
| 9 | + |
| 10 | +[Jest DynamoDB](https://github.com/shelfio/jest-dynamodb) provides all required configuration to run your tests using DynamoDB. |
| 11 | + |
| 12 | +1. First install `@shelf/jest-dynamodb` |
| 13 | + |
| 14 | +``` |
| 15 | +yarn add @shelf/jest-dynamodb --dev |
| 16 | +``` |
| 17 | + |
| 18 | +2. Specify preset in your Jest configuration: |
| 19 | + |
| 20 | +```json |
| 21 | +{ |
| 22 | + "preset": "@shelf/jest-dynamodb" |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +3. Create `jest-dynamodb-config.js` and define DynamoDB tables |
| 27 | + |
| 28 | +See [Create Table API](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property) |
| 29 | + |
| 30 | +```js |
| 31 | +module.exports = { |
| 32 | + tables: [ |
| 33 | + { |
| 34 | + TableName: `files`, |
| 35 | + KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}], |
| 36 | + AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}], |
| 37 | + ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}, |
| 38 | + }, |
| 39 | + // etc |
| 40 | + ], |
| 41 | +}; |
| 42 | +``` |
| 43 | + |
| 44 | +4. Configure DynamoDB client |
| 45 | + |
| 46 | +```js |
| 47 | +const {DocumentClient} = require('aws-sdk/clients/dynamodb'); |
| 48 | + |
| 49 | +const isTest = process.env.JEST_WORKER_ID; |
| 50 | +const config = { |
| 51 | + convertEmptyValues: true, |
| 52 | + ...(isTest && { |
| 53 | + endpoint: 'localhost:8000', |
| 54 | + sslEnabled: false, |
| 55 | + region: 'local-env', |
| 56 | + }), |
| 57 | +}; |
| 58 | + |
| 59 | +const ddb = new DocumentClient(config); |
| 60 | +``` |
| 61 | + |
| 62 | +5. Write tests |
| 63 | + |
| 64 | +```js |
| 65 | +it('should insert item into table', async () => { |
| 66 | + await ddb |
| 67 | + .put({TableName: 'files', Item: {id: '1', hello: 'world'}}) |
| 68 | + .promise(); |
| 69 | + |
| 70 | + const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise(); |
| 71 | + |
| 72 | + expect(Item).toEqual({ |
| 73 | + id: '1', |
| 74 | + hello: 'world', |
| 75 | + }); |
| 76 | +}); |
| 77 | +``` |
| 78 | + |
| 79 | +There's no need to load any dependencies. |
| 80 | + |
| 81 | +See [documentation](https://github.com/shelfio/jest-dynamodb) for details. |
0 commit comments