What is testcontainers?
The testcontainers npm package is a library that provides lightweight, throwaway instances of common databases, Selenium web browsers, or anything else that can run in a Docker container. It is primarily used for integration testing, allowing developers to run tests against real instances of services without the overhead of managing those services manually.
What are testcontainers's main functionalities?
Running a PostgreSQL container
This feature allows you to run a PostgreSQL container for testing purposes. The code sample demonstrates how to start a PostgreSQL container with a specified password and expose the default port.
const { GenericContainer } = require('testcontainers');
(async () => {
const container = await new GenericContainer('postgres')
.withEnv('POSTGRES_PASSWORD', 'password')
.withExposedPorts(5432)
.start();
console.log(`PostgreSQL started on port ${container.getMappedPort(5432)}`);
})();
Running a Redis container
This feature allows you to run a Redis container for testing purposes. The code sample demonstrates how to start a Redis container and expose the default port.
const { GenericContainer } = require('testcontainers');
(async () => {
const container = await new GenericContainer('redis')
.withExposedPorts(6379)
.start();
console.log(`Redis started on port ${container.getMappedPort(6379)}`);
})();
Running a custom Docker container
This feature allows you to run any custom Docker container for testing purposes. The code sample demonstrates how to start a custom Docker container and expose a specified port.
const { GenericContainer } = require('testcontainers');
(async () => {
const container = await new GenericContainer('your-custom-image')
.withExposedPorts(8080)
.start();
console.log(`Custom container started on port ${container.getMappedPort(8080)}`);
})();
Other packages similar to testcontainers
dockerode
Dockerode is a Docker client for Node.js. It provides a way to interact with Docker containers programmatically. While it offers more control and flexibility over Docker operations, it lacks the high-level abstractions and ease of use that testcontainers provides for integration testing.
node-docker-api
Node-docker-api is another Docker client for Node.js. Similar to dockerode, it allows for programmatic interaction with Docker containers. However, it does not provide the same level of convenience and specialized features for testing as testcontainers.