Join our Discord Server
Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).

Getting started with Testcontainers for Node.js

2 min read

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:

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

Have Queries? Join https://launchpass.com/collabnix

Ajeet Raina Ajeet Singh Raina is a former Docker Captain, Community Leader and Distinguished Arm Ambassador. He is a founder of Collabnix blogging site and has authored more than 700+ blogs on Docker, Kubernetes and Cloud-Native Technology. He runs a community Slack of 9800+ members and discord server close to 2600+ members. You can follow him on Twitter(@ajeetsraina).
Join our Discord Server
Index