This guide configures GitLab CI/CD for a NodeJS project and adds a unit testing job with environment variable management.
In this guide, we’ll configure GitLab CI/CD for the Solar System NodeJS project and add a robust unit testing job. You’ll learn how to create a structured .gitlab-ci.yml, manage sensitive MongoDB credentials via CI/CD variables, and ensure your NodeJS tests run reliably.
Specify when the pipeline should trigger by adding a workflow section with conditional rules:
Copy
Ask AI
workflow: name: Solar System NodeJS Pipeline rules: # Run on pushes to main or feature branches - if: $CI_COMMIT_BRANCH == "main" || $CI_COMMIT_BRANCH =~ /^feature/ when: always # Run on merge request events from feature branches - if: $CI_MERGE_REQUEST_SOURCE_BRANCH_NAME =~ /^feature/ && $CI_PIPELINE_SOURCE == "merge_request_event" when: alwaysstages: - test
Inspect the job logs. The runner pulls the NodeJS image and installs packages, but npm test fails with a Mongoose connection error. Our application code in app.js relies on environment variables:
$ npm installadded 364 packages, and audited 365 packages in 8s44 packages are looking for fundingRun `npm fund` for detailsvulnerabilities (1 high, 1 critical)To address all issues, run: npm audit fix$ npm test> Solar [email protected] test> mocha app-test.js --timeout 10000 --reporter mocha-junit-reporter --exitServer successfully running on port 3000 ✓ should return all planets ✓ should return planet by ID ...
Now that unit tests are passing, the next step is to collect test reports using the artifacts keyword.