### Create and Start a Network, then a Container Source: https://node.testcontainers.org/features/networking Demonstrates how to create a new network, start a container within that network, and then stop both. Ensure the 'testcontainers' package is installed. ```javascript const { GenericContainer, Network } = require("testcontainers"); const network = await new Network().start(); const container = await new GenericContainer("alpine") .withNetwork(network) .start(); await container.stop(); await network.stop(); ``` -------------------------------- ### Datastore Emulator Example Source: https://node.testcontainers.org/modules/gcloud Example of using the Datastore emulator with Testcontainers. This snippet shows how to start the emulator, configure the Datastore client, and perform save and get operations. ```typescript await using container = await new DatastoreEmulatorContainer(image).start(); const datastore = new Datastore({ projectId: "test-project", apiEndpoint: container.getEmulatorEndpoint(), }); const key = datastore.key(["test-kind", "123"]); const data = { message: "Hello, Datastore!" }; await datastore.save({ key, data }); const [entity] = await datastore.get(key); expect(entity).toEqual({ message: "Hello, Datastore!", [Datastore.KEY]: key }); ``` -------------------------------- ### Start a Generic Container Source: https://node.testcontainers.org/features/containers Starts a generic container with the specified image. Ensure the 'testcontainers' library is installed. ```javascript const { GenericContainer } = require("testcontainers"); const container = await new GenericContainer("alpine").start(); ``` -------------------------------- ### Cloud Storage Emulator Example Source: https://node.testcontainers.org/modules/gcloud Example of using the Cloud Storage emulator with Testcontainers. This snippet shows how to start the emulator, configure the Storage client, and create a bucket. ```typescript await using container = await new CloudStorageEmulatorContainer(IMAGE).start(); const storage = new Storage({ projectId: "test-project", apiEndpoint: container.getExternalUrl(), }); await storage.createBucket("test-bucket"); const [buckets] = await storage.getBuckets(); expect(buckets[0].name).toBe("test-bucket"); ``` -------------------------------- ### Connect to RabbitMQ with Credentials Source: https://node.testcontainers.org/modules/rabbitmq Example showing how to start a RabbitMQ container with custom environment variables for username and password, and then connect using these credentials. The container's mapped port for the AMQP protocol is used for the connection. ```javascript const USER = "user"; const PASSWORD = "password"; await using container = await new RabbitMQContainer(IMAGE) .withEnvironment({ RABBITMQ_DEFAULT_USER: USER, RABBITMQ_DEFAULT_PASS: PASSWORD, }) .start(); const connection = await amqp.connect({ username: USER, password: PASSWORD, port: container.getMappedPort(5672), }); ``` -------------------------------- ### Install Azure Cosmos DB SDK Source: https://node.testcontainers.org/modules/cosmosdb Install the @azure/cosmos SDK for interacting with Cosmos DB. This is required for the examples. ```bash npm install @azure/cosmos ``` -------------------------------- ### Create an OpenSearch Index Source: https://node.testcontainers.org/modules/opensearch This example demonstrates how to start an OpenSearch container and create an index named 'people' using the OpenSearch client. ```javascript await using container = await new OpenSearchContainer(image).start(); const client = new Client({ node: container.getHttpUrl(), auth: { username: container.getUsername(), password: container.getPassword(), }, ssl: { rejectUnauthorized: false, }, }); await client.indices.create({ index: "people" }); const { body } = await client.indices.exists({ index: "people" }); expect(body).toBe(true); ``` -------------------------------- ### Start Oracle Database and Execute Queries Source: https://node.testcontainers.org/modules/oraclefree Starts an Oracle database container with custom configurations and executes queries against it using the oracledb driver. Ensure the oracledb package is installed and imported. ```javascript const customDatabase = "TESTDB"; const customUsername = "CUSTOMUSER"; const customPassword = "customPassword"; await using container = await new OracleDbContainer(IMAGE) .withDatabase(customDatabase) .withUsername(customUsername) .withPassword(customPassword) .start(); const connection = await oracledb.getConnection({ user: container.getUsername(), password: container.getPassword(), connectString: container.getUrl(), }); const result = await connection.execute("SELECT SYS_CONTEXT('USERENV', 'CON_NAME') FROM DUAL"); expect(result.rows![0]).toEqual([customDatabase]); const resultUser = await connection.execute("SELECT USER FROM DUAL"); expect(resultUser.rows![0]).toEqual([customUsername]); await connection.close(); ``` -------------------------------- ### Cloud Pub/Sub Emulator Example Source: https://node.testcontainers.org/modules/gcloud Example of using the Cloud Pub/Sub emulator with Testcontainers. This snippet demonstrates starting the emulator and creating a topic. ```typescript await using container = await new PubSubEmulatorContainer(IMAGE).start(); const pubSub = new PubSub({ projectId: "test-project", apiEndpoint: container.getEmulatorEndpoint(), }); const [createdTopic] = await pubSub.createTopic("test-topic"); expect(createdTopic.name).toContain("test-topic"); ``` -------------------------------- ### Install @google-cloud/datastore Source: https://node.testcontainers.org/modules/gcloud Install the Datastore client library for Node.js. ```bash npm install @google-cloud/datastore ``` -------------------------------- ### Install Nano Library Source: https://node.testcontainers.org/modules/couchdb Install the nano library, a popular Node.js client for CouchDB. This is used in the examples. ```bash npm install nano ``` -------------------------------- ### Install MQTT Client Library Source: https://node.testcontainers.org/modules/hivemq Install the MQTT client library for Node.js. ```bash npm install mqtt ``` -------------------------------- ### Install mysql2 Driver Source: https://node.testcontainers.org/modules/mysql Install the mysql2 library, a popular Node.js driver for MySQL, which is used in the examples. ```bash npm install mysql2 ``` -------------------------------- ### Spanner Emulator Example: Connect via Client Source: https://node.testcontainers.org/modules/gcloud Example of connecting to the Spanner emulator via the client library. This snippet demonstrates starting the emulator and verifying instance configuration. ```typescript await using container = await new SpannerEmulatorContainer(IMAGE).withProjectId("test-project").start(); const spanner = new Spanner({ projectId: container.getProjectId(), apiEndpoint: container.getHost(), port: container.getGrpcPort(), sslCreds: container.getSslCredentials(), }); const admin = spanner.getInstanceAdminClient(); const [configs] = await admin.listInstanceConfigs({ parent: admin.projectPath(container.getProjectId()), }); const expectedConfigName = admin.instanceConfigPath(container.getProjectId(), "emulator-config"); expect(configs.map((c) => c.name)).toContain(expectedConfigName); ``` -------------------------------- ### Install PostgreSQL Client Source: https://node.testcontainers.org/modules/cockroachdb Install the 'pg' library and its types for interacting with CockroachDB. ```bash npm install pg npm install @types/pg --save-dev ``` -------------------------------- ### Install MinIO Client Source: https://node.testcontainers.org/modules/minio Install the official MinIO client library for Node.js. ```bash npm install minio ``` -------------------------------- ### Install @google-cloud/storage Source: https://node.testcontainers.org/modules/gcloud Install the Cloud Storage client library for Node.js. ```bash npm install @google-cloud/storage ``` -------------------------------- ### Install Testcontainers and Redis Dependencies Source: https://node.testcontainers.org/quickstart/usage Install the necessary npm packages for Testcontainers and Redis. This is a prerequisite for running the examples. ```bash npm install testcontainers --save-dev npm install redis ``` -------------------------------- ### Install amqplib Source: https://node.testcontainers.org/modules/rabbitmq Install the amqplib library and its types for interacting with RabbitMQ. ```bash npm install amqplib npm install @types/amqplib --save-dev ``` -------------------------------- ### Install Qdrant JS Client Source: https://node.testcontainers.org/modules/qdrant Install the official Qdrant JavaScript client library. ```bash npm install @qdrant/js-client-rest ``` -------------------------------- ### Setup Redis Container Globally Source: https://node.testcontainers.org/quickstart/global-setup Use this script to start a Redis container once and make its connection URL available to your tests. ```javascript import { RedisContainer } from "@testcontainers/redis"; let redisContainer; export async function setup(project) { redisContainer = await new RedisContainer("redis:8").start(); project.provide("redisUrl", redisContainer.getConnectionUrl()); } export async function teardown() { await redisContainer?.stop(); } ``` -------------------------------- ### Install @kubernetes/client-node Source: https://node.testcontainers.org/modules/k3s Install the Kubernetes client library for Node.js. ```bash npm install @kubernetes/client-node ``` -------------------------------- ### Install Superagent Source: https://node.testcontainers.org/modules/mockserver Install the superagent library and its types for Node.js. Superagent is used for making HTTP requests in the examples. ```bash npm install superagent npm install @types/superagent --save-dev ``` -------------------------------- ### Navigate to a Page with Selenium Source: https://node.testcontainers.org/modules/selenium Example of starting a Selenium container, building a WebDriver instance, navigating to a URL, and verifying the page title. ```typescript await using container = await new SeleniumContainer(image).start(); const driver = await new Builder().forBrowser(Browser[browser]).usingServer(container.getServerUrl()).build(); await driver.get("https://testcontainers.com"); expect(await driver.getTitle()).toEqual("Testcontainers"); await driver.quit(); ``` -------------------------------- ### Install @google-cloud/firestore Source: https://node.testcontainers.org/modules/gcloud Install the Firestore client library for Node.js. ```bash npm install @google-cloud/firestore ``` -------------------------------- ### Install Weaviate TS Client Source: https://node.testcontainers.org/modules/weaviate Install the weaviate-ts-client library for interacting with Weaviate. ```bash npm install weaviate-ts-client ``` -------------------------------- ### Create an S3 Bucket with S3Mock Source: https://node.testcontainers.org/modules/s3mock Example demonstrating how to start an S3Mock container, create an S3 client, and create a bucket. This is useful for testing S3 interactions without a real S3 service. ```typescript await using container = await new S3MockContainer(IMAGE).start(); const client = new S3Client({ endpoint: container.getHttpConnectionUrl(), forcePathStyle: true, region: "auto", credentials: { secretAccessKey: container.getSecretAccessKey(), accessKeyId: container.getAccessKeyId(), }, }); const input = { Bucket: "testcontainers" }; const command = new CreateBucketCommand(input); expect((await client.send(command)).$metadata.httpStatusCode).toEqual(200); expect((await client.send(new HeadBucketCommand(input))).$metadata.httpStatusCode).toEqual(200); ``` -------------------------------- ### Valkey with Initial Data Source: https://node.testcontainers.org/modules/valkey Shows how to pre-populate a Valkey container with data from a file using `withInitialData`. The example verifies that the predefined data is accessible after the container starts. ```typescript await using container = await new ValkeyContainer(IMAGE) .withPassword("test") .withInitialData(path.join(__dirname, "initData.valkey")) .start(); const client = createClient({ url: container.getConnectionUrl() }); await client.connect(); const user = { first_name: "David", last_name: "Bloom", dob: "03-MAR-1981", }; expect(await client.get("user:002")).toBe(JSON.stringify(user)); client.destroy(); ``` -------------------------------- ### Record Video with Selenium Source: https://node.testcontainers.org/modules/selenium Example demonstrating how to start a Selenium container with video recording enabled, navigate a page, stop the container, save the recording, and verify it using FFmpeg. ```typescript const container = await new SeleniumContainer(image).withRecording().start(); const driver = await new Builder().forBrowser(Browser[browser]).usingServer(container.getServerUrl()).build(); await driver.get("https://testcontainers.com"); await driver.quit(); const stoppedContainer = await container.stop(); const videoFilePath = tmp.fileSync({ keep: false, prefix: `video-${browser}`, postfix: ".mp4" }).name; const videoFileName = path.basename(videoFilePath); await stoppedContainer.saveRecording(videoFilePath); await using ffmpegContainer = await new GenericContainer(SELENIUM_VIDEO_IMAGE) .withCommand(["sleep", "infinity"]) .start(); await ffmpegContainer.copyFilesToContainer([{ source: videoFilePath, target: `/tmp/${videoFileName}` }]); const { exitCode } = await ffmpegContainer.exec(["ffprobe", `/tmp/${videoFileName}`]); expect(exitCode).toBe(0); ``` -------------------------------- ### Execute a Query with KurrentDB Source: https://node.testcontainers.org/modules/kurrentdb Demonstrates how to start a KurrentDB container, connect a client, append an event to a stream, and read the stream. Ensure you have the necessary client library installed. ```typescript await using container = await new KurrentDbContainer(IMAGE).start(); const client = KurrentDBClient.connectionString(container.getConnectionString()); await client.appendToStream("User-1", [ { contentType: "application/json", data: { email: "john@foo.local" }, type: "UserCreated", id: "28ab6bca-d9ae-418b-a1af-eb65dd653c38", metadata: { someMetadata: "bar" }, }, ]); expect(await consumeSteamingRead(client.readStream("User-1"))).toEqual([ expect.objectContaining({ event: expect.objectContaining({ data: { email: "john@foo.local" }, id: "28ab6bca-d9ae-418b-a1af-eb65dd653c38", isJson: true, metadata: { someMetadata: "bar" }, revision: 0, streamId: "User-1", type: "UserCreated", }), }), ]); await client.dispose(); async function consumeSteamingRead(read: AsyncIterableIterator): Promise { const events = []; for await (const event of read) { events.push(event); } return events; } ``` -------------------------------- ### Install MariaDB Client Source: https://node.testcontainers.org/modules/mariadb Install the official mariadb Node.js client library. ```bash npm install mariadb ``` -------------------------------- ### Install Redis Client Source: https://node.testcontainers.org/modules/redis Install the official Redis client library for Node.js. ```bash npm install redis ``` -------------------------------- ### Install etcd3 client Source: https://node.testcontainers.org/modules/etcd Install the etcd3 client library for Node.js. ```bash npm install etcd3 ``` -------------------------------- ### Install @google-cloud/pubsub Source: https://node.testcontainers.org/modules/gcloud Install the Cloud Pub/Sub client library for Node.js. ```bash npm install @google-cloud/pubsub ``` -------------------------------- ### Execute a Query with CosmosDB Emulator Source: https://node.testcontainers.org/modules/cosmosdb This example demonstrates how to start a CosmosDB emulator container, create a database and container, and execute a query using the @azure/cosmos SDK. Ensure you have an image from Microsoft Artifact Registry specified by IMAGE. ```typescript const dbName = "testdb"; const containerName = "testcontainer"; await using container = await new AzureCosmosDbEmulatorContainer(IMAGE).withProtocol("http").start(); const cosmosClient = new CosmosClient({ endpoint: container.getEndpoint(), key: container.getKey(), }); await cosmosClient.databases.createIfNotExists({ id: dbName }); const dbClient = cosmosClient.database(dbName); 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"); ``` -------------------------------- ### Install KurrentDB Client Source: https://node.testcontainers.org/modules/kurrentdb Install the KurrentDB client library for Node.js. ```bash npm install @kurrent/kurrentdb-client ``` -------------------------------- ### Install @clickhouse/client Source: https://node.testcontainers.org/modules/clickhouse Install the official ClickHouse client library for Node.js. ```bash npm install @clickhouse/client ``` -------------------------------- ### Configure Valkey with Username and Password Source: https://node.testcontainers.org/modules/valkey Demonstrates starting a Valkey container with both a username and a password, and verifying the generated connection URL. Use `withUsername` and `withPassword` for authentication setup. ```typescript const username = "testUser"; const password = "testPassword"; await using container = await new ValkeyContainer(IMAGE).withUsername(username).withPassword(password).start(); expect(container.getConnectionUrl()).toEqual( `redis://${username}:${password}@${container.getHost()}:${container.getPort()}` ); ``` -------------------------------- ### Install Mockserver Client Source: https://node.testcontainers.org/modules/mockserver Install the mockserver-client library for Node.js. This is required for interacting with the Mockserver. ```bash npm install mockserver-client ``` -------------------------------- ### Install Azure Storage Queue SDK Source: https://node.testcontainers.org/modules/azurite Install the @azure/storage-queue SDK for interacting with Azure Queue Storage. ```bash npm install @azure/storage-queue ``` -------------------------------- ### Install ChromaDB Libraries Source: https://node.testcontainers.org/modules/chromadb Install the necessary ChromaDB client libraries for Node.js. ```bash npm install chromadb ``` ```bash npm install @chroma-core/default-embed ``` ```bash npm install @chroma-core/ollama ``` -------------------------------- ### Install Cassandra Driver Source: https://node.testcontainers.org/modules/cassandra Install the official Cassandra driver for Node.js. ```bash npm install cassandra-driver ``` -------------------------------- ### Install OpenSearch Client Source: https://node.testcontainers.org/modules/opensearch Install the official OpenSearch client library for Node.js using npm. ```bash npm install @opensearch-project/opensearch ``` -------------------------------- ### Read and write key-value pairs with Etcd Source: https://node.testcontainers.org/modules/etcd Demonstrates how to start an Etcd container, connect to it using the etcd3 client, and perform basic put and get operations. ```typescript await using container = await new EtcdContainer(IMAGE).start(); const client = new Etcd3({ hosts: container.getClientEndpoint(), }); const key = "foo"; const value = "bar"; await client.put(key).value(value); const result = await client.get(key).string(); expect(result).toEqual(value); ``` -------------------------------- ### Install Toxiproxy Node Client Source: https://node.testcontainers.org/modules/toxiproxy Install the toxiproxy-node-client package using npm. ```bash npm install @testcontainers/toxiproxy --save-dev ``` -------------------------------- ### Install Toxiproxy Node Client Source: https://node.testcontainers.org/modules/toxiproxy Install the toxiproxy-node-client package using npm. ```bash npm install toxiproxy-node-client ``` -------------------------------- ### Install @google-cloud/spanner Source: https://node.testcontainers.org/modules/gcloud Install the Cloud Spanner client library for Node.js. ```bash npm install @google-cloud/spanner ``` -------------------------------- ### Produce and Consume a Message with RabbitMQ Source: https://node.testcontainers.org/modules/rabbitmq Example demonstrating how to produce a message to a queue and consume it using Testcontainers and amqplib. Ensure the RabbitMQ container is started before attempting to connect. ```javascript const QUEUE = "test"; const PAYLOAD = "Hello World"; await using container = await new RabbitMQContainer(IMAGE).start(); const connection = await amqp.connect(container.getAmqpUrl()); const channel = await connection.createChannel(); await channel.assertQueue(QUEUE); channel.sendToQueue(QUEUE, Buffer.from(PAYLOAD)); await new Promise((resolve) => { channel.consume(QUEUE, (message) => { expect(message?.content.toString()).toEqual(PAYLOAD); resolve(true); }); }); await channel.close(); await connection.close(); ``` -------------------------------- ### Install Selenium WebDriver Source: https://node.testcontainers.org/modules/selenium Install the selenium-webdriver package and its types for Node.js. ```bash npm install selenium-webdriver npm install @types/selenium-webdriver --save-dev ``` -------------------------------- ### Install BigQuery Client Library Source: https://node.testcontainers.org/modules/gcloud Installs the necessary Node.js client library for Google Cloud BigQuery. ```bash npm install @google-cloud/bigquery ``` -------------------------------- ### Test Redis Container with GenericContainer Source: https://node.testcontainers.org/quickstart/usage This example shows how to start a Redis container using GenericContainer, connect to it, and perform a simple set/get operation. It requires the 'redis' and 'testcontainers' packages. ```typescript import { createClient, RedisClientType } from "redis"; import { GenericContainer, StartedTestContainer } from "testcontainers"; describe("Redis", () => { let container: StartedTestContainer; let redisClient: RedisClientType; beforeAll(async () => { container = await new GenericContainer("redis:8") .withExposedPorts(6379) .start(); redisClient = createClient({ url: `redis://${container.getHost()}:${container.getMappedPort(6379)}` }); await redisClient.connect(); }); afterAll(async () => { await redisClient.disconnect(); await container.stop(); }); it("works", async () => { await redisClient.set("key", "val"); expect(await redisClient.get("key")).toBe("val"); }); }); ``` -------------------------------- ### Install Mongoose Source: https://node.testcontainers.org/modules/mongodb Install the Mongoose ODM for interacting with MongoDB. ```bash npm install mongoose ``` -------------------------------- ### Connect to CosmosDB Emulator with HTTPS Source: https://node.testcontainers.org/modules/cosmosdb This example shows how to start a CosmosDB emulator container using HTTPS and configure the Cosmos Client to connect securely. It includes setting up an HTTPS agent to bypass certificate validation for local testing. ```typescript await using container = await new AzureCosmosDbEmulatorContainer(IMAGE).withProtocol("https").start(); const cosmosClient = new CosmosClient({ endpoint: container.getEndpoint(), key: container.getKey(), agent: new https.Agent({ rejectUnauthorized: false, }), }); ``` -------------------------------- ### Install Neo4j Driver Source: https://node.testcontainers.org/modules/neo4j Install the neo4j-driver library for interacting with Neo4j. ```bash npm install neo4j-driver ``` -------------------------------- ### Install S3Mock Source: https://node.testcontainers.org/modules/s3mock Install the S3Mock package as a development dependency. ```bash npm install @testcontainers/s3mock --save-dev ``` -------------------------------- ### Install Kafka JavaScript Client Source: https://node.testcontainers.org/modules/kafka Install the Confluent Kafka JavaScript client library. ```bash npm install @confluentinc/kafka-javascript ``` -------------------------------- ### Mock HTTP Request with Mockserver Source: https://node.testcontainers.org/modules/mockserver Start a Mockserver container and mock a GET request to '/foo' to return 'bar'. This example demonstrates basic HTTP request mocking. ```typescript await using container = await new MockserverContainer(IMAGE).start(); const client = mockServerClient(container.getHost(), container.getMockserverPort()); await client.mockAnyResponse({ httpRequest: { method: "GET", path: "/foo", }, httpResponse: { body: { string: "bar", }, statusCode: 200, }, }); const response = await superagent.get(`${container.getUrl()}/foo`); expect(response.statusCode).toBe(200); expect(response.text).toBe("bar"); ``` -------------------------------- ### Provide Log Consumer Before Container Start Source: https://node.testcontainers.org/features/containers Configure a log consumer before starting the container. This is useful for debugging containers that fail to start, as logs can be captured immediately. ```javascript const container = await new GenericContainer("alpine") .withLogConsumer(stream => { stream.on("data", line => console.log(line)); stream.on("err", line => console.error(line)); stream.on("end", () => console.log("Stream closed")); }) .start(); ``` -------------------------------- ### Start a Generic Container with an Entrypoint Source: https://node.testcontainers.org/features/containers Starts a generic container and overrides the default entrypoint. This is useful for changing the primary executable that runs when the container starts. ```javascript const container = await new GenericContainer("alpine") .withEntrypoint(["cat"]) .start(); ``` -------------------------------- ### Install Couchbase SDK Source: https://node.testcontainers.org/modules/couchbase Install the Couchbase SDK for Node.js using npm. ```bash npm install couchbase ``` -------------------------------- ### Install KurrentDB Source: https://node.testcontainers.org/modules/kurrentdb Install the KurrentDB module for Node.js using npm. ```bash npm install @testcontainers/kurrentdb --save-dev ``` -------------------------------- ### Start a Generic Container with Bind Mounts Source: https://node.testcontainers.org/features/containers Starts a generic container with bind mounts. Note: Bind mounts are not recommended for portability and may not work in all Docker environments. Prefer copying files instead. ```javascript const container = await new GenericContainer("alpine") .withBindMounts([{ source: "/local/file.txt", target:"/remote/file.txt" }, { source: "/local/dir", target:"/remote/dir", mode: "ro" }]) .start(); ``` -------------------------------- ### Start Qdrant Container with Config File Source: https://node.testcontainers.org/modules/qdrant Start a Qdrant container using a configuration file. Ensure the config file path is correctly resolved. ```typescript await using container = await new QdrantContainer(IMAGE) .withConfigFile(path.resolve(__dirname, "test_config.yaml")) .start(); const client = new QdrantClient({ url: `http://${container.getRestHostAddress()}`, apiKey: "SOME_TEST_KEY" }); ``` -------------------------------- ### Install Azure Data Tables SDK Source: https://node.testcontainers.org/modules/azurite Install the @azure/data-tables SDK for interacting with Azure Table Storage. ```bash npm install @azure/data-tables ``` -------------------------------- ### Install Redis Module for Testcontainers Source: https://node.testcontainers.org/quickstart/usage Install the dedicated Redis module for Testcontainers to simplify Redis container setup. This is an alternative to using GenericContainer. ```bash npm install @testcontainers/redis --save-dev ``` -------------------------------- ### Install Azure Storage Blob SDK Source: https://node.testcontainers.org/modules/azurite Install the @azure/storage-blob SDK for interacting with Azure Blob Storage. ```bash npm install @azure/storage-blob ``` -------------------------------- ### Install PostgreSQL Testcontainer Source: https://node.testcontainers.org/modules/postgresql Install the PostgreSQL Testcontainers module for Node.js. ```bash npm install @testcontainers/postgresql --save-dev ``` -------------------------------- ### MinIO with Custom Credentials Source: https://node.testcontainers.org/modules/minio Shows how to start a MinIO container with custom username and password, and then use these credentials to connect and create a bucket. ```typescript await using container = await new MinioContainer(IMAGE) .withUsername("AzureDiamond") .withPassword("hunter2!") .start(); const client = new minio.Client({ endPoint: container.getHost(), port: container.getPort(), useSSL: false, accessKey: "AzureDiamond", secretKey: "hunter2!", }); await client.makeBucket("test-bucket"); const bucketExits = await client.bucketExists("test-bucket"); expect(bucketExits).toBeTruthy(); ``` -------------------------------- ### Install Valkey Module Source: https://node.testcontainers.org/modules/valkey Install the Valkey module using npm. This is a prerequisite for using Valkey with Testcontainers. ```bash npm install @testcontainers/valkey --save-dev ``` -------------------------------- ### Install Qdrant Testcontainers Source: https://node.testcontainers.org/modules/qdrant Install the Qdrant Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/qdrant --save-dev ``` -------------------------------- ### Composite Wait Strategy with Individual Startup Timeouts Source: https://node.testcontainers.org/features/wait-strategies Demonstrates setting individual startup timeouts for strategies within a composite Wait.forAll strategy. ```javascript const w1 = Wait.forListeningPorts().withStartupTimeout(1000); // 1 second const w2 = Wait.forLogMessage("READY").withStartupTimeout(2000); // 2 seconds const composite = Wait.forAll([w1, w2]); expect(w1.getStartupTimeout()).toBe(1000); expect(w2.getStartupTimeout()).toBe(2000); ``` -------------------------------- ### Install node-vault Library Source: https://node.testcontainers.org/modules/vault Install the node-vault library, which is used to interact with Vault. ```bash npm install node-vault ``` -------------------------------- ### Install Selenium Testcontainers Source: https://node.testcontainers.org/modules/selenium Install the Selenium Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/selenium --save-dev ``` -------------------------------- ### Install Weaviate Testcontainers Source: https://node.testcontainers.org/modules/weaviate Install the Weaviate Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/weaviate --save-dev ``` -------------------------------- ### Produce and Consume with SSL Enabled Kafka Container Source: https://node.testcontainers.org/modules/kafka Starts a Kafka container with SSL enabled and demonstrates producing and consuming messages. Requires certificate setup. ```typescript await using container = await new KafkaContainer("confluentinc/cp-kafka:7.5.0") .withSaslSslListener({ port: 9096, sasl: { mechanism: "SCRAM-SHA-512", user: { name: "app-user", password: "userPassword", }, }, keystore: { content: fs.readFileSync(path.resolve(certificatesDir, "kafka.server.keystore.pfx")), passphrase: "serverKeystorePassword", }, truststore: { content: fs.readFileSync(path.resolve(certificatesDir, "kafka.server.truststore.pfx")), passphrase: "serverTruststorePassword", }, }) .start(); await assertMessageProducedAndConsumed( container, { brokers: [`${container.getHost()}:${container.getMappedPort(9096)}`], ssl: true, sasl: { mechanism: "scram-sha-512", username: "app-user", password: "userPassword", }, }, { "ssl.ca.location": path.resolve(certificatesDir, "kafka.client.truststore.pem"), } ); ``` ```typescript export async function assertMessageProducedAndConsumed( container: StartedKafkaContainer, additionalKafkaConfig: Partial = {}, additionalGlobalConfig: Partial = {} ) { const brokers = [`${container.getHost()}:${container.getMappedPort(9093)}`]; const kafka = new KafkaJS.Kafka({ kafkaJS: { logLevel: KafkaJS.logLevel.ERROR, brokers, ...additionalKafkaConfig, }, ...additionalGlobalConfig, }); const producer = kafka.producer(); await producer.connect(); const consumer = kafka.consumer({ kafkaJS: { groupId: "test-group", fromBeginning: true } }); await consumer.connect(); await producer.send({ topic: "test-topic", messages: [{ value: "test message" }] }); await consumer.subscribe({ topic: "test-topic" }); const consumedMessage = await new Promise((resolve) => consumer.run({ eachMessage: async ({ message }) => resolve(message.value?.toString()), }) ); expect(consumedMessage).toBe("test message"); await consumer.disconnect(); await producer.disconnect(); } ``` -------------------------------- ### Install Oracle Database Driver Source: https://node.testcontainers.org/modules/oraclefree Install the oracledb package to interact with the Oracle database. ```bash npm install oracledb ``` -------------------------------- ### Install OpenSearch Testcontainers Source: https://node.testcontainers.org/modules/opensearch Install the OpenSearch Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/opensearch --save-dev ``` -------------------------------- ### Install Cassandra Testcontainers Source: https://node.testcontainers.org/modules/cassandra Install the Cassandra Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/cassandra --save-dev ``` -------------------------------- ### Install Azurite for development Source: https://node.testcontainers.org/modules/azurite Install the Azurite package as a development dependency using npm. ```bash npm install @testcontainers/azurite --save-dev ``` -------------------------------- ### Connect to Redpanda REST Proxy Source: https://node.testcontainers.org/modules/redpanda Starts a Redpanda container and constructs the REST proxy URL for topics. It then makes a GET request to this URL to verify connectivity. ```typescript await using container = await new RedpandaContainer(IMAGE).start(); const restProxyUrl = `${container.getRestProxyAddress()}/topics`; const response = await fetch(restProxyUrl); expect(response.status).toBe(200); ``` -------------------------------- ### Connect to Redpanda Schema Registry Source: https://node.testcontainers.org/modules/redpanda Starts a Redpanda container and retrieves the schema registry URL. It then makes a GET request to the /subjects endpoint to verify connectivity. ```typescript await using container = await new RedpandaContainer(IMAGE).start(); const schemaRegistryUrl = container.getSchemaRegistryAddress(); const response = await fetch(`${schemaRegistryUrl}/subjects`, { method: "GET", headers: { "Content-Type": "application/vnd.schemaregistry.v1+json", }, }); expect(response.status).toBe(200); ``` -------------------------------- ### Install MySQL Testcontainers Source: https://node.testcontainers.org/modules/mysql Install the MySQL Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/mysql --save-dev ``` -------------------------------- ### Set and Get a Value with Redis Container Source: https://node.testcontainers.org/modules/redis Demonstrates how to start a Redis container, connect to it using the redis client, set a value, retrieve it, and then destroy the client. ```typescript await using container = await new RedisContainer(IMAGE).start(); const client = createClient({ url: container.getConnectionUrl() }); await client.connect(); await client.set("key", "val"); expect(await client.get("key")).toBe("val"); client.destroy(); ``` -------------------------------- ### Mock HTTPS Request with Mockserver Source: https://node.testcontainers.org/modules/mockserver Start a Mockserver container and mock an HTTPS GET request to '/foo'. Note that MockServer uses a self-signed certificate for HTTPS. ```typescript await using container = await new MockserverContainer(IMAGE).start(); const client = mockServerClient(container.getHost(), container.getMockserverPort()); await client.mockAnyResponse({ httpRequest: { method: "GET", path: "/foo", }, httpResponse: { body: { string: "bar", }, statusCode: 200, }, }); const secureUrl = container.getSecureUrl(); const response = await superagent.get(`${secureUrl}/foo`).disableTLSCerts(); expect(response.statusCode).toBe(200); expect(response.text).toBe("bar"); ``` -------------------------------- ### Install MinIO Testcontainers Source: https://node.testcontainers.org/modules/minio Install the MinIO Testcontainers module for Node.js using npm. ```bash npm install @testcontainers/minio --save-dev ``` -------------------------------- ### Kafka Container with Kraft Mode Source: https://node.testcontainers.org/modules/kafka Starts a Kafka container in Kraft mode, which is the successor to ZooKeeper for Kafka metadata management. This is the recommended setup for newer Kafka versions. ```typescript await using container = await new KafkaContainer(IMAGE).withKraft().start(); ``` -------------------------------- ### Start CockroachDB Container with Custom Database Source: https://node.testcontainers.org/modules/cockroachdb Start a CockroachDB container and specify a custom database name. ```typescript await using container = await new CockroachDbContainer(IMAGE).withDatabase("custom_database").start(); ``` -------------------------------- ### Connect to Redpanda Admin API Source: https://node.testcontainers.org/modules/redpanda Starts a Redpanda container and constructs the admin API URL. It then makes a GET request to the root of the admin API to verify connectivity. ```typescript await using container = await new RedpandaContainer(IMAGE).start(); const adminUrl = `${container.getAdminAddress()}/v1`; const response = await fetch(adminUrl); expect(response.status).toBe(200); ``` -------------------------------- ### Produce and Consume MQTT Message with HiveMQ Container Source: https://node.testcontainers.org/modules/hivemq Start a HiveMQ container and use an MQTT client to publish and subscribe to messages. Ensure you have an MQTT client library installed. ```typescript await using container = await new HiveMQContainer(IMAGE).start(); const mqttClient = await mqtt.connectAsync(container.getConnectionString()); const firstMessagePromise = new Promise<{ topic: string; message: Buffer }>((resolve, reject) => { mqttClient.once("message", (topic, message) => resolve({ topic, message })); mqttClient.once("error", (err) => reject(err)); }); await mqttClient.subscribeAsync("test"); await mqttClient.publishAsync("test", "Test Message"); const { message } = await firstMessagePromise; expect(message.toString()).toEqual("Test Message"); mqttClient.end(); ``` -------------------------------- ### Start a Pod in K3s Cluster Source: https://node.testcontainers.org/modules/k3s Starts a K3s container and deploys a 'helloworld' pod. It waits for the pod to be in a Running state. ```typescript await using container = await new K3sContainer(IMAGE).start(); const kubeConfig = new k8s.KubeConfig(); kubeConfig.loadFromString(container.getKubeConfig()); const pod = { metadata: { name: "helloworld", }, spec: { containers: [ { name: "helloworld", image: "testcontainers/helloworld:1.1.0", ports: [ { containerPort: 8080, }, ], readinessProbe: { tcpSocket: { port: 8080, }, }, }, ], }, }; const client = kubeConfig.makeApiClient(k8s.CoreV1Api); await client.createNamespacedPod({ namespace: "default", body: pod }); await vi.waitFor(async () => { const { status } = await client.readNamespacedPodStatus({ namespace: "default", name: "helloworld" }); return ( status?.phase === "Running" && status?.conditions?.some((cond) => cond.type === "Ready" && cond.status === "True") ); }, 60_000); ``` -------------------------------- ### Test Redis Container with RedisModule Source: https://node.testcontainers.org/quickstart/usage This example demonstrates a simplified way to start and test a Redis container using the dedicated '@testcontainers/redis' module. It connects and performs a set/get operation. ```typescript import { createClient, RedisClientType } from "redis"; import { RedisContainer, StartedRedisContainer } from "@testcontainers/redis"; describe("Redis", () => { let container: StartedRedisContainer; let redisClient: RedisClientType; beforeAll(async () => { container = await new RedisContainer("redis:8").start(); redisClient = createClient({ url: container.getConnectionUrl() }); await redisClient.connect(); }); afterAll(async () => { await redisClient.disconnect(); await container.stop(); }); it("works", async () => { await redisClient.set("key", "val"); expect(await redisClient.get("key")).toBe("val"); }); }); ``` -------------------------------- ### Configure MariaDB with a Custom Database Source: https://node.testcontainers.org/modules/mariadb Start a MariaDB container with a specific database name and connect to it. Verifies the current database in the session. ```javascript await using container = await new MariaDbContainer(IMAGE).withDatabase("customDatabase").start(); const client = await mariadb.createConnection({ host: container.getHost(), port: container.getPort(), database: container.getDatabase(), user: container.getUsername(), password: container.getUserPassword(), }); const rows = await client.query("SELECT DATABASE() as res"); expect(rows).toEqual([{ res: "customDatabase" }]); await client.end(); ``` -------------------------------- ### Execute a Query with ArangoDB Testcontainers Source: https://node.testcontainers.org/modules/arangodb Start an ArangoDB container, connect to it using the arangojs driver, and execute a simple query. Ensure you have the arangojs library installed and the correct image name for ArangoDB. ```javascript await using container = await new ArangoDBContainer(IMAGE).start(); const db = new Database({ url: container.getHttpUrl() }); db.database("_system"); db.useBasicAuth(container.getUsername(), container.getPassword()); const value = "Hello ArangoDB!"; const result = await db.query({ query: "RETURN @value", bindVars: { value }, }); const returnValue = await result.next(); expect(returnValue).toBe(value); ``` -------------------------------- ### Send and Receive Queue Messages Source: https://node.testcontainers.org/modules/azureservicebus Example demonstrating sending a message to a queue and then receiving it using the Azure Service Bus Testcontainers and SDK. Ensure the container is started and the connection string is obtained. ```typescript await using container = await new AzureServiceBusContainer(IMAGE).acceptLicense().start(); const client = new ServiceBusClient(container.getConnectionString()); const sender = client.createSender("queue.1"); const receiver = client.createReceiver("queue.1"); await sender.sendMessages({ body: "Hello, World!" }); const res = await receiver.receiveMessages(1, { maxWaitTimeInMs: 5_000 }); expect(res).toHaveLength(1); expect(res[0].body).toBe("Hello, World!"); await receiver.close(); await sender.close(); await client.close(); ``` -------------------------------- ### Run CLI Init Commands at Startup Source: https://node.testcontainers.org/modules/vault Configure the Vault container to run CLI init commands when it starts, such as enabling secrets engines or writing initial configurations. This example enables the transit secrets engine and creates a key. ```javascript await using container = await new VaultContainer(IMAGE) .withVaultToken(VAULT_TOKEN) .withInitCommands("secrets enable transit", "write -f transit/keys/my-key") .start(); const result = await container.exec(["vault", "read", "-format=json", "transit/keys/my-key"]); expect(result.exitCode).toBe(0); expect(result.output).toContain("my-key"); ``` -------------------------------- ### Configure Authentication for ChromaDB Source: https://node.testcontainers.org/modules/chromadb Set up ChromaDB with token-based authentication by configuring environment variables and headers. This example demonstrates creating tenants, databases, and collections with authentication. ```typescript const tenant = "test-tenant"; const key = "test-key"; const database = "test-db"; await using container = await new ChromaDBContainer(IMAGE) .withEnvironment({ CHROMA_SERVER_AUTHN_CREDENTIALS: key, CHROMA_SERVER_AUTHN_PROVIDER: "chromadb.auth.token_authn.TokenAuthenticationServerProvider", CHROMA_AUTH_TOKEN_TRANSPORT_HEADER: "X-Chroma-Token", }) .start(); const adminClient = new AdminClient({ ssl: false, host: container.getHost(), port: container.getMappedPort(8000), headers: { "X-Chroma-Token": key, }, }); await adminClient.createTenant({ name: tenant }); await adminClient.createDatabase({ name: database, tenant: tenant }); const dbClient = new ChromaClient({ tenant, ssl: false, host: container.getHost(), port: container.getMappedPort(8000), headers: { "X-Chroma-Token": key, }, database, }); const collection = await dbClient.createCollection({ name: "test-collection" }); expect(collection.name).toBe("test-collection"); ``` -------------------------------- ### Start Docker Compose Environment Source: https://node.testcontainers.org/features/compose Create and start a Docker Compose environment using the specified compose file path and file name. ```javascript const { DockerComposeEnvironment } = require("testcontainers"); const composeFilePath = "/path/to/build-context"; const composeFile = "docker-compose.yml"; const environment = await new DockerComposeEnvironment(composeFilePath, composeFile).up(); ``` -------------------------------- ### Install @testcontainers/gcloud Source: https://node.testcontainers.org/modules/gcloud Install the GCloud Testcontainers module for Node.js. ```bash npm install @testcontainers/gcloud --save-dev ``` -------------------------------- ### Start a Generic Container with Environment Variables Source: https://node.testcontainers.org/features/containers Starts a generic container and sets environment variables within it. This allows for configuration of the container's runtime environment. ```javascript const container = await new GenericContainer("alpine") .withEnvironment({ ENV: "VALUE" }) .start(); ``` -------------------------------- ### Start Qdrant Container with API Key Source: https://node.testcontainers.org/modules/qdrant Configure a Qdrant container to use an API key for authentication and initialize the client with it. ```typescript const apiKey = crypto.randomUUID(); await using container = await new QdrantContainer(IMAGE).withApiKey(apiKey).start(); const client = new QdrantClient({ url: `http://${container.getRestHostAddress()}`, apiKey }); ``` -------------------------------- ### Install @testcontainers/clickhouse Source: https://node.testcontainers.org/modules/clickhouse Install the ClickHouse Testcontainers module for Node.js. ```bash npm install @testcontainers/clickhouse --save-dev ``` -------------------------------- ### Install Kafka Testcontainers Source: https://node.testcontainers.org/modules/kafka Install the Kafka Testcontainers module for Node.js. ```bash npm install @testcontainers/kafka --save-dev ``` -------------------------------- ### Start Container with Bridge Network Mode Source: https://node.testcontainers.org/features/networking Illustrates starting a container using the 'bridge' network mode. Note that some network modes, like 'host', are Linux-specific. ```javascript const container = await new GenericContainer("alpine") .withNetworkMode("bridge") .start(); ``` -------------------------------- ### Start MSSQL Server Testcontainer with Express edition Source: https://node.testcontainers.org/modules/mssqlserver Start an MSSQL Server container, accept its license, set the edition to Express using withEnvironment, and wait for a specific message indicating initialization. ```typescript await using container = await new MSSQLServerContainer(IMAGE) .acceptLicense() .withEnvironment({ MSSQL_PID: "Express" }) .withWaitForMessage(/.*Attribute synchronization manager initialized*/) .start(); ``` -------------------------------- ### Install @testcontainers/k3s Source: https://node.testcontainers.org/modules/k3s Install the K3s module for Testcontainers using npm. ```bash npm install @testcontainers/k3s --save-dev ``` -------------------------------- ### Install Azure Service Bus SDK Source: https://node.testcontainers.org/modules/azureservicebus Install the official Azure Service Bus SDK for Node.js using npm. ```bash npm install @azure/service-bus ``` -------------------------------- ### Install AWS SDK S3 Client Source: https://node.testcontainers.org/modules/localstack Install the AWS SDK S3 client for Node.js using npm. ```bash npm install @aws-sdk/client-s3 ``` -------------------------------- ### Start a Generic Container with Specific Version Source: https://node.testcontainers.org/features/containers Starts a generic container using a specific image version. This ensures consistency across environments. ```javascript const container = await new GenericContainer("alpine:3.10").start(); ``` -------------------------------- ### Start a Generic Container with a Platform Source: https://node.testcontainers.org/features/containers Starts a generic container on a specified platform, such as 'linux/arm64'. This is analogous to the '--platform' flag in Docker. ```javascript const container = await new GenericContainer("alpine") .withPlatform("linux/arm64") // similar to `--platform linux/arm64` .start(); ``` -------------------------------- ### Install Nats Jetstream Source: https://node.testcontainers.org/modules/nats Install the @nats-io/jetstream library for Nats JetStream functionality. ```bash npm install @nats-io/jetstream ``` -------------------------------- ### Install Nats Transport Node Source: https://node.testcontainers.org/modules/nats Install the @nats-io/transport-node library for Nats communication. ```bash npm install @nats-io/transport-node ``` -------------------------------- ### Configure Vitest for Global Setup Source: https://node.testcontainers.org/quickstart/global-setup Configure your Vitest project to use the global setup script by specifying its path in the `vitest.config.js` file. ```javascript import { defineConfig } from "vitest/config"; export default defineConfig({ test: { globalSetup: "./setup.js", }, }); ``` -------------------------------- ### Install Nats Module Source: https://node.testcontainers.org/modules/nats Install the Nats module for Testcontainers using npm. ```bash npm install @testcontainers/nats --save-dev ``` -------------------------------- ### Configure Valkey with Password Source: https://node.testcontainers.org/modules/valkey Shows how to start a Valkey container with a password and verify the connection URL. The `withPassword` method is used for this configuration. ```typescript const password = "testPassword"; await using container = await new ValkeyContainer(IMAGE).withPassword(password).start(); expect(container.getConnectionUrl()).toEqual(`redis://:${password}@${container.getHost()}:${container.getPort()}`); ``` -------------------------------- ### Configure MySQL Credentials Source: https://node.testcontainers.org/modules/mysql Start a MySQL container with custom username, password, and database name. It also demonstrates how to retrieve the connection URI and how to set a root password. ```typescript const username = "testUser"; const password = "testPassword"; const database = "testDB"; await using container = await new MySqlContainer(IMAGE) .withUsername(username) .withUserPassword(password) .withDatabase(database) .start(); expect(container.getConnectionUri()).toEqual( `mysql://${username}:${password}@${container.getHost()}:${container.getPort()}/${database}` ); await using rootContainer = await new MySqlContainer(IMAGE) .withRootPassword(password) .withDatabase(database) .start(); expect(rootContainer.getConnectionUri(true)).toEqual( `mysql://root:${password}@${rootContainer.getHost()}:${rootContainer.getPort()}/${database}` ); ``` -------------------------------- ### Execute CouchDB Query with Credentials Source: https://node.testcontainers.org/modules/couchdb Example demonstrating how to connect to a CouchDB instance with custom credentials. It sets a username and password for the container and verifies the connection URL. ```javascript await using container = await new CouchDBContainer(IMAGE).withUsername("admin").withPassword("foo").start(); const client = nano({ url: container.getUrl(), }); await client.db.create("users"); const db = client.use("users"); const document = await db.insert({ username: "j-doe", email: "j-doe@mail.local", }); expect(container.getUrl()).toBe(`http://admin:foo@${container.getHost()}:${container.getPort()}`); expect(await db.get(document.id)).toEqual({ _id: document.id, _rev: document.rev, username: "j-doe", email: "j-doe@mail.local", }); ``` -------------------------------- ### Start and Use BigQuery Emulator Container Source: https://node.testcontainers.org/modules/gcloud Starts a BigQuery emulator container and uses it to create a dataset, table, insert data, and retrieve rows. ```typescript await using container = await new BigQueryEmulatorContainer(IMAGE).start(); const bigQuery = new BigQuery({ projectId: container.getProjectId(), apiEndpoint: container.getEmulatorEndpoint(), }); const dataset = "test-dataset"; const table = "test-table"; const schema: TableSchema = { fields: [{ name: "message", type: "STRING" }] }; await bigQuery.dataset(dataset).create(); await bigQuery.dataset(dataset).table(table).create({ schema: schema }); await bigQuery .dataset(dataset) .table(table) .insert([{ message: "Hello, BigQuery!" }]); const [rows] = await bigQuery.dataset(dataset).table(table).getRows(); expect(rows).toEqual([{ message: "Hello, BigQuery!" }]); ```