13.1.2.1 CI Unit Containers
A focused guide to CI Unit Containers, connecting core concepts with practical Docker and container operations.
CI unit containers run an application's unit tests within a container specifically scoped to that fast, isolated testing purpose, generally not requiring any external dependencies like a database, making them simple and quick to run as an early, fast-feedback stage in a CI pipeline.
Why Unit Tests Typically Don't Need External Dependencies
By definition, a well-written unit test exercises a small, isolated piece of code, typically using mocks or stubs for anything that would otherwise require an external dependency like a database or external API.
docker run --rm myapp:test npm run test:unit
This command alone, with no additional services running, is sufficient since unit tests shouldn't require genuine external dependencies in the first place.
Why This Makes Unit Test Containers Fast to Run in CI
Without needing to wait for a database or other external service to start and become ready, a unit test container can start and run its tests very quickly, providing fast feedback early in a pipeline.
jobs:
unit-tests:
steps:
- run: docker build --target test -t myapp:test .
- run: docker run --rm myapp:test npm run test:unit
Structuring CI to Run Unit Tests Before More Expensive Stages
Running this fast unit test stage before slower stages (integration tests, image scanning) provides quicker feedback for the most common kind of failure, without waiting for slower checks to also complete.
jobs:
unit-tests:
steps: [...]
integration-tests:
needs: unit-tests
steps: [...]
A pipeline structured this way fails fast on a unit test failure, without unnecessarily running the more expensive integration test stage first.
Capturing Unit Test Coverage From the Container Run
Coverage reports generated during the unit test run can be extracted for further reporting or enforcement of a coverage threshold.
docker run --rm -v $(pwd)/coverage:/app/coverage myapp:test npm run test:unit -- --coverage
Why CI Unit Containers Matter
Running unit tests within a simple, dependency-free container provides fast, reliable feedback early in a CI pipeline, an efficient first checkpoint before investing in the additional time and complexity slower integration testing stages require.