Run Node.js tests in a container
Prerequisites
Complete all the previous sections of this guide, starting with Containerize a Node.js application.
Overview
Testing is a core part of building reliable software. Docker makes it easy to run your tests in the same environment used in CI and production, so failures are caught before they reach your users.
In this section, you'll add Vitest to the project and run tests both locally and inside a container.
Update the application
You'll refactor src/index.ts to export the Express app instance so tests
can import it without starting a server. Add a test file and update
package.json to add Vitest and a test runner for HTTP requests. The file browser shows only the files that change in this step.
Run tests locally
Run the following command to run the tests locally:
$ npm install
$ npm test
You should see output like the following:
RUN v3.0.0 /app
✓ src/index.test.ts (1)
✓ GET / (1)
✓ returns a JSON greeting
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 12:00:00
Duration 500ms
Run tests in a container
Run the tests using the dev stage of your Dockerfile:
$ docker compose run --build --rm --no-deps server npm test
The --no-deps flag skips starting the database, since the unit tests don't require it. The --rm flag removes the container when the tests finish.
You should see the same test output as when running locally.
Run tests when building
To run tests during the Docker build process, add a test stage to your Dockerfile that runs after the dev stage.
FROM dhi.io/node:24-alpine3.23-dev AS dev
WORKDIR /app
RUN --mount=type=cache,target=/root/.npm \
--mount=type=bind,source=package.json,target=package.json \
npm install
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "run", "dev"]
FROM dhi.io/node:24-alpine3.23-dev AS deps
WORKDIR /app
RUN --mount=type=cache,target=/root/.npm \
--mount=type=bind,source=package.json,target=package.json \
npm install --omit=dev
FROM dhi.io/node:24-alpine3.23 AS runner
ENV PATH=/app/node_modules/.bin:$PATH
WORKDIR /app
COPY --from=deps --chown=node:node /app/node_modules ./node_modules
COPY --from=dev --chown=node:node /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/index.js"]
FROM dev AS test
ENV CI=true
CMD ["npm", "test"]Then build and run the test stage:
$ docker build --target test -t nodejs-app-test .
$ docker run --rm nodejs-app-test
Summary
In this section, you learned how to run tests when developing locally and inside a container.
Related information:
Next steps
In the next section, you'll learn how to set up a CI/CD pipeline using GitHub Actions.