This content originally appeared on DEV Community and was authored by Ajeet Singh Raina
In the world of software development, testing is a crucial aspect that ensures the reliability and performance of applications. Testcontainers is a popular library that simplifies the process of integration testing by providing lightweight, disposable containers for your tests.
What is Testcontainers?
Testcontainers is a Java library that allows developers to use Docker containers for integration testing. It provides a simple API to spin up containers for various services, such as databases, message brokers, and web servers, ensuring that your tests run in a consistent and isolated environment. While Testcontainers was originally designed for Java, it has been extended to support other languages, including Node.js.
You might find these blogs useful:
- How to Run Hugging Face Models Programmatically Using Ollama and Testcontainers
- Develop Kubernetes Operators in Java without Breaking a Sweat
- A Promising Methodology for Testing GenAI Applications in Java
- Building Spring Boot’s ServiceConnection for Testcontainers WireMock
This blog post will guide you through the basics of getting started with Testcontainers for Node.js, helping you to set up your testing environment and write effective tests using containers.
Clone the repo
git clone https://github.com/dockersamples/docker-init-demos
cd docker-init-demos
Install Testcontainers for Node.js
First, you need to install Testcontainers for Node.js. You can add it as a dependency to your project using npm:
npm install --save testcontainers
added 138 packages, and audited 139 packages in 38s
21 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
Create a test file
Create a new file named app.test.js
(or any other name you prefer) in your project directory.
Import the necessary modules: In your test file, import the required modules:
const { TestContainers } = require('testcontainers');
const { GenericContainer } = require('testcontainers');
const http = require('http');
const assert = require('assert');
Set up Testcontainers
Create an instance of TestContainers and configure it to use Docker:
const testcontainers = new TestContainers();
testcontainers.setDefaultTimeout(10000);
Create a Docker container for your Node.js application
Use the GenericContainer class to create a Docker container for your Node.js application. Make sure to replace with the actual path to your Node.js application:
const nodeContainer = new GenericContainer('node:14')
.withWorkingDirectory('/app')
.withCopyFile('<path_to_your_app>', '/app')
.withExposedPorts(8080)
.withCommand('node', 'app.js');
Start the Docker container
Use the start() method to start the Docker container:
await nodeContainer.start();
Test your application
Use the http module to send a request to your application running inside the Docker container and assert the response:
const response = await new Promise((resolve, reject) => {
const request = http.get(`http://localhost:${nodeContainer.getMappedPort(8080)}`, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
});
request.on('error', (error) => {
reject(error);
});
});
assert.strictEqual(response.trim(), `
## .
## ## ## ==
## ## ## ## ## ===
/""""""""""""""""\\___/ ===
{ / ===-
\\______ O __/
\\ \\ __/
\\____\\_______/
Hello from Docker!
`);
Stop the Docker container
Use the stop() method to stop the Docker container after the test:
await nodeContainer.stop();
Now you can run your test using a test runner like Jest or Mocha. Make sure to include the test file in your test configuration.
The overall app.test.js file should look like:
const { TestContainers } = require('testcontainers');
const { GenericContainer } = require('testcontainers');
const http = require('http');
const assert = require('assert');
const testcontainers = new TestContainers();
testcontainers.setDefaultTimeout(10000);
const nodeContainer = new GenericContainer('node:14')
.withWorkingDirectory('/app')
.withCopyFile('<path_to_your_app>', '/app')
.withExposedPorts(8080)
.withCommand('node', 'app.js');
await nodeContainer.start();
const response = await new Promise((resolve, reject) => {
const request = http.get(`http://localhost:${nodeContainer.getMappedPort(8080)}`, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
});
request.on('error', (error) => {
reject(error);
});
});
assert.strictEqual(response.trim(), `
## .
## ## ## ==
## ## ## ## ## ===
/""""""""""""""""\\___/ ===
{ / ===-
\\______ O __/
\\ \\ __/
\\____\\_______/
Hello from Docker!
`);
await nodeContainer.stop();
Install Mocha
Install Mocha as a development dependency to your project using npm:
npm install --save-dev mocha
Conclusion
Testcontainers is a powerful tool that can significantly enhance your testing strategy by providing isolated environments for your integration tests. By following the steps outlined in this blog post, you should now have a basic understanding of how to set up and use Testcontainers with Node.js. As you become more familiar with the library, you can explore additional features such as custom containers, waiting for containers to be ready, and more.
Happy testing!
References
- Testcontainers Best Practices
- Streamlining Local Development with Dev Containers and Testcontainers Cloud
This content originally appeared on DEV Community and was authored by Ajeet Singh Raina
Ajeet Singh Raina | Sciencx (2024-09-13T10:22:41+00:00) Getting started with Testcontainers for Node.js. Retrieved from https://www.scien.cx/2024/09/13/getting-started-with-testcontainers-for-node-js/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.