User Agents

Web browsers and everyday web tech, explained

Docker Image for Karma Tests with Headless Chrome

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide walks you through creating a Docker image that runs Karma unit tests using Headless Chrome. By containerizing your test environment, you ensure consistent browser behavior across all developer machines and CI servers, eliminating the classic "works on my machine" problem. You'll end up with a reusable Dockerfile that installs Node.js, Chrome, and your project dependencies, then runs your Karma test suite headlessly.

What You'll Need

  • A project with a package.json that includes Karma and a Karma configuration file (e.g., karma.conf.js).
  • Docker installed on your machine (version 20.10 or later recommended).
  • Basic familiarity with the command line.

Step-by-Step

  1. Review your Karma configuration. Ensure your karma.conf.js uses the ChromeHeadless launcher. If not, install karma-chrome-launcher and set browsers: ['ChromeHeadless']. Also set singleRun: true so tests exit after completion.
  2. Create a Dockerfile in your project root. Start with a Node.js base image, for example FROM node:18-slim. This gives you a minimal Linux environment with Node and npm.
  3. Install Chromium and dependencies. Headless Chrome needs certain system libraries. Add the following to your Dockerfile:
    RUN apt-get update && apt-get install -y \
        chromium \
        fonts-liberation \
        libappindicator3-1 \
        libasound2 \
        libatk-bridge2.0-0 \
        libatk1.0-0 \
        libcups2 \
        libdbus-1-3 \
        libgdk-pixbuf2.0-0 \
        libnspr4 \
        libnss3 \
        libx11-xcb1 \
        libxcomposite1 \
        libxdamage1 \
        libxrandr2 \
        xdg-utils \
        --no-install-recommends
    On Debian-based images, the package is named chromium (not google-chrome).
  4. Set environment variables to tell Chrome to run in headless mode and to avoid sandbox issues in containers. Add:
    ENV CHROME_BIN=/usr/bin/chromium
    ENV CI=true
    The CHROME_BIN variable tells Karma which Chrome binary to use. The CI variable makes Karma run in CI mode (which implies single run).
  5. Copy your package files and install dependencies. This leverages Docker layer caching:
    WORKDIR /app
    COPY package*.json ./
    RUN npm install
    If you use npm ci for exact versions, replace the RUN line with RUN npm ci.
  6. Copy the rest of your source code. Add COPY . . to bring in your tests, source, and Karma config.
  7. Define the command to run tests. Add:
    CMD ["npm", "test"]
    This assumes your package.json has a "test" script that runs Karma (e.g., "test": "karma start --single-run"). Adjust if needed.
  8. Build the image. From your project root, run:
    docker build -t karma-tests .
    This creates an image tagged karma-tests.
  9. Run the container. Execute:
    docker run --rm karma-tests
    The --rm flag removes the container after it finishes, keeping your system clean. You should see Karma output and a success/failure summary.

Common Mistakes

  • Forgetting to set CHROME_BIN – Karma will not find Chrome and will throw a launcher error.
  • Using the wrong package name – On Debian/Ubuntu, it's chromium, not google-chrome-stable. Using the latter will cause apt-get to fail.
  • Not installing all required system libraries – Chrome may crash with missing shared libraries. The list in Step 3 covers common ones, but if you get errors, add the missing packages.
  • Running with sandbox enabled – Chrome's sandbox often fails in Docker. You must either set the --no-sandbox flag in your Karma config or use the CHROME_BIN environment variable as shown. The simplest is to add customLaunchers in Karma config:
    customLaunchers: {
      ChromeHeadlessNoSandbox: {
        base: 'ChromeHeadless',
        flags: ['--no-sandbox']
      }
    }
    Then set browsers: ['ChromeHeadlessNoSandbox'].

Tips

  • Use a specific Node version – Pinning to a major version (e.g., node:18-slim) ensures reproducibility. Avoid latest tags.
  • Leverage Docker layer caching – Copy package.json and package-lock.json before your source code so npm install only runs when dependencies change.
  • Add a .dockerignore file – Exclude node_modules, .git, and other unnecessary files to speed up builds and reduce image size.
  • Use multi-stage builds for smaller images – If you need to keep the image small, consider a multi-stage build where you install dependencies in one stage and copy only the necessary artifacts to a fresh stage.
  • Run tests with --rm and --volume for live development – You can mount your source code into the container: docker run --rm -v $(pwd):/app karma-tests to test changes without rebuilding the image.

Troubleshooting

  • Error: "Chrome failed to start" – Check that CHROME_BIN points to the correct binary. Run which chromium inside the container to verify. Also ensure all system libraries are installed.
  • Error: "Missing X server or $DISPLAY" – This usually means Chrome is trying to run in headed mode. Make sure you're using ChromeHeadless and that CI=true is set.
  • Error: "Could not find the binary 'google-chrome'" – You're using the wrong launcher or the wrong binary name. Set CHROME_BIN=/usr/bin/chromium or update your Karma config to use the correct custom launcher.
  • Tests run but hang – This often happens when Karma is not set to singleRun. Set singleRun: true in your config, or pass --single-run in your npm test script.
  • Permission denied errors – If you see EACCES errors, ensure your container user has write access to the working directory. You can run the container with --user $(id -u):$(id -g) to match your host user.

Frequently Asked Questions

Can I use Google Chrome instead of Chromium?

Yes, but you'd need to install the proprietary Google Chrome .deb package, which requires downloading from Google's servers. Chromium is open-source and available in Debian's repositories, making it easier and more license-friendly for CI.

Why do I need to add --no-sandbox?

Chrome's sandbox relies on kernel features that are often disabled in Docker containers. Without the flag, Chrome may crash or refuse to run. It's a common and accepted workaround for containerized testing.

How do I pass environment variables to my tests?

Use the -e flag with docker run, e.g., docker run -e MY_VAR=value karma-tests. Your tests can read them via process.env.

Can I use this image for other Node.js tasks?

Yes, the image includes Node.js and npm, so you can run any Node command by overriding the default command, e.g., docker run karma-tests node -v.

How do I debug failing tests inside the container?

Run the container interactively with docker run -it karma-tests /bin/bash. Then you can manually run npm test and inspect the environment. You can also mount your source code with -v to edit files live.

What if my tests need a database or other services?

You can use Docker Compose to define multiple services (e.g., a database container) and run your test container alongside them. Or you can use the --network flag to connect to an existing network.