Skip to content

Cosmos DB Emulator Module (Linux-based)

Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft.

Install

npm install @testcontainers/azurecosmosdb --save-dev

Examples

it("should be able to create a database using http", async () => {
  const container = await new AzureCosmosDbEmulatorContainer().withProtocol("http").start();
  const cosmosClient = new CosmosClient({
    endpoint: container.getEndpoint(),
    key: container.getKey(),
  });

  const dbName = "testdb";
  const createResponse = await cosmosClient.databases.createIfNotExists({
    id: dbName,
  });
  expect(createResponse.statusCode).toBe(201);

  const db = await cosmosClient.database(dbName).read();
  expect(db.database.id).toBe(dbName);

  await container.stop();
});
it("should be able to create a database using https", async () => {
  const container = await new AzureCosmosDbEmulatorContainer().withProtocol("https").start();
  const cosmosClient = new CosmosClient({
    endpoint: container.getEndpoint(),
    key: container.getKey(),
    agent: new https.Agent({
      rejectUnauthorized: false, //allows insecure TLS; import * as https from "node:https";
    }),
  });

  const dbName = "testdb";
  const createResponse = await cosmosClient.databases.createIfNotExists({
    id: dbName,
  });
  expect(createResponse.statusCode).toBe(201);

  const db = await cosmosClient.database(dbName).read();
  expect(db.database.id).toBe(dbName);

  await container.stop();
});
it("should be able to create a container and store and retrieve items", async () => {
  const container = await new AzureCosmosDbEmulatorContainer().withProtocol("http").start();
  const cosmosClient = new CosmosClient({
    endpoint: container.getEndpoint(),
    key: container.getKey(),
  });

  const dbName = "testdb";
  await cosmosClient.databases.createIfNotExists({
    id: dbName,
  });
  const dbClient = cosmosClient.database(dbName);

  const containerName = "testcontainer";
  await dbClient.containers.createIfNotExists({
    id: containerName,
    partitionKey: {
      kind: PartitionKeyKind.Hash,
      paths: ["/foo"],
    },
  });

  const containerClient = dbClient.container(containerName);
  const createResponse = await containerClient.items.create({
    foo: "bar",
  });

  const readItem = await containerClient.item(createResponse.item.id, "bar").read();
  expect(readItem.resource.foo).toEqual("bar");

  await container.stop();
});

Caveats

Compatibility

This testcontainer uses the linux-based version. In general, it:

  • Provides better compatibility on a variety of systems
  • Consumes significantly less resources
  • Comes with much faster startup times

However, not all features of a full CosmosDB are implemented yet - please refer to this overview for a detailed list.