Keep node_modules between stages

I’m trying to install node_modules/ in one stage and then run tests in a separate stage. These need to be in separate stages because I’ll have multiple test jobs in the same stage, and I don’t want to redo package installation

This is my gitlab-ci.yml file. It might be overkill (artifacts + cache + dependencies), but I can’t figure out what’s needed:

image: node:7.9

stages:
  - setup
  - test

setup:
  stage: setup
  script:
    - npm install --unsafe-perm
  cache:
    paths:
      - node_modules/
  artifacts:
    untracked: true
    paths:
     - node_modules/

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

My setup job ends with this:

Creating cache default...
Created cache
Uploading artifacts...
node_modules/: found 14374 matching files          
untracked: found 12811 files                       
WARNING: Uploading artifacts to coordinator... failed  id=4115 responseStatus=500 Internal Server Error status=500 Internal Server Error token=4sKJfG_x
WARNING: Retrying...                               
WARNING: Uploading artifacts to coordinator... failed  id=4115 responseStatus=500 Internal Server Error status=500 Internal Server Error token=4sKJfG_x
FATAL: invalid argument                            
Job succeeded

So it seems the cache works, although the artifacts do not.

My test job includes this:

Fetching changes...
Removing build/
Removing node_modules/

I don’t want it to remove node_modules/. How can I prevent this from happening?

Fix:

image: node:7.9

stages:
  - setup
  - test

cache:
  paths:
    - node_modules/

setup:
  stage: setup
  script:
    - npm install --unsafe-perm

test:
  stage: test
  script:
    - npm test

… but I didn’t stick with this, because it looks like you need to run npm install using the same version of node that you test with, so there’s no use in putting it in a separate stage (besides the cleanliness of seeing what stage failed).

This doesn’t work in Gitlab CI 10.2. There is no node_module/ directory in the “test” stage, so npm installs all modules from scratch each time.