To do integration tests with your DynamoDB Toolbox setup, it's important to be able to run tests in isolations. Otherwise, different tests could set up the data in a way that breaks other tests. With parallel and randomized execution, this could lead to flaky tests. Flaky tests == sad developers and wasted time, so we definitely want to avoid that.
To achieve true isolation we need each test case to use a separate DynamoDB table. That means, we need to do the Table setup using a different table name.
If you prefer watching from reading, you can watch me here add the tests:
Currently, the src/Customer.ts file only exposes the Customer Entity and does not allow any kind of dynamic configuration. Let's create a function that will return that Customer Entity, but will allow taking a custom table.
This way we can pass custom tableName and documentClient.
Now we are able to use dynamodb-testing-tool to do some testing.
Install it first:
npm install --save-dev dynamodb-testing-tool
Let's create Customer.spec.ts and do some setup.
We will start with a single test:
test("Putting and getting a Customer", async () => {})
First, we need to create an in-memory DynamoDB Table with a randomly generated name (to avoid collisions and achieve isolation):
import { createTable, generateRandomName } from "dynamodb-testing-tool";
import { tableDefinition } from "./tableDefinition";
test("Putting and getting a Customer", async () => {
const tableObject = await createTable({
...tableDefinition,
TableName: generateRandomName(),
});
})
Now we want to get a Customer Entity that uses a ToolboxTable configured with that randomName and matching documentClient.
import { createTable, generateRandomName } from "dynamodb-testing-tool";
import { tableDefinition } from "./tableDefinition";
// Import the getter functions we made earlier:
import { getToolboxTable, getCustomerEntity } from "./Customer";
test("Putting and getting a Customer", async () => {
const tableObject = await createTable({
...tableDefinition,
TableName: generateRandomName(),
});
// Declare and initialize the Customer variable here
const Customer = getCustomerEntity(
getToolboxTable(tableObject.tableName, tableObject.documentClient)
);
})
As you can see, the createTable function returns an object on which you can find the tableName (which we randomly generated) and the documentClient associated with that table.