
Module 5 Lesson 1: Automated Unit Testing
The first line of defense. Learn how to integrate unit tests into your GitLab pipeline, use test reports, and visualize your code coverage.
Module 5 Lesson 1: Automated Unit Testing
If your code doesn't work, there is no point in building or deploying it. Unit Testing is the foundation of the CI (Continuous Integration) cycle.
1. Running the Test Job
A unit test job usually follows the "Build" stage. It is fast and only tests individual functions.
test-unit:
stage: test
image: node:18
script:
- npm install
- npm test
2. JUnit Reports (Project Management)
If you have 1,000 tests and 1 fails, scrolling through a 500-page "Console Log" is painful. GitLab can parse your test results and show them in a beautiful UI.
test-unit:
script:
- npm test -- --reporters=junit --outputFile=report.xml
artifacts:
reports:
junit: report.xml
Now, the pipeline page will have a "Tests" tab showing exactly which test failed and why.
3. Code Coverage Visualization
Code coverage tells you: "What % of my lines of code are actually tested?" GitLab can show this directly in your Merge Request (Pull Request).
test-unit:
script:
- npm test -- --coverage
coverage: '/Code coverage: \d+\.\d+/' # A Regex to find the number in the log
4. Failing vs. Warnings
Should a failing test block the deployment? Usually, yes.
However, for an "Experimental" test suite, you might use:
allow_failure: true
Exercise: The Safety Net
- Write a simple Python function (e.g.,
add(a, b)) and a test for it (unittestorpytest). - Create a GitLab CI job that runs this test.
- Intentional Failure: Break your function (
return a - b) and push. - Observe the pipeline. Does it stop the process?
- Search: How do you show a "Code Coverage Badge" on your project's main page?
- Why is 100% coverage often a "False Goal"?
Summary
Unit testing in GitLab turns your "Code" into "Verifiable Facts." By using JUnit reports and coverage metrics, you give your team and your stakeholders the confidence that the software does exactly what is intended.
Next Lesson: Beyond individual functions: Integration Testing and Service Containers.