Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a test in Gitlab for nodejs application

I am new to gitlab so don't have a lot of knowledge about it.

I am trying to setup gitlab to run a test before it builds the image. I have set up a private runner which is configured properly and I can build images but it doesn't work if I run an npm command to test the code. Here is my gitlab-ci.yml file.

image: docker:latest
variables:
  IMAGE_TAG: $CI_REGISTRY_IMAGE:$CI_COMMIT_REF_NAME
services:
- docker:dind
before_script:
  - docker login -u gitlab-ci-token -p "$CI_BUILD_TOKEN" "$CI_REGISTRY"

stages:
  - build-container-test
  - test-run


build-container-test:
  stage: build-container-test
  script:
    - docker build -t "$IMAGE_TAG" .
    - docker push "$IMAGE_TAG"
  only:
    - test

test-run:
  stage: test-run
  script:
    - npm run test
  only:
    - test

This is the error I get while running it. enter image description here

Do I need to have npm installed separately on gitlab runner to run it or am I missing something here ?

like image 784
Anshul Tripathi Avatar asked Sep 12 '25 06:09

Anshul Tripathi


1 Answers

An ease example of gitlab-ci file to run the test in the CI:

image: node:23.1.0

stages:
  - npm
  - test

npm:
  stage: npm
  script:
    - npm config set registry ${CI_NPM_REGISTRY}
    - npm install
  cache:
    paths:
      - node_modules/
  artifacts:
    expire_in: 1 days
    when: on_success
    paths:
      - node_modules/

test:
  stage: test
  dependencies:
    - npm
  script:
    - npm test

UPDATE

I split the pipelines in two, the first one is for install all the dependencies, in this job is used the artifacts, the artifacts are for share data between jobs (you can see the documentation). Then in the test job you can run the tests.

Answering the question about environment variables:

  • Yes, you can use environment variables, go to the CI/CD configurations and in the Environments variables you can defined you own variables and mark as protected or not (to use this env variables see the documentation)
like image 69
Guillermo González Avatar answered Sep 13 '25 19:09

Guillermo González