I’m working with a multi-stage Docker setup where I want to keep my final image lightweight. In my first build stage, I install all the npm dependencies and tools. Then in the second stage, I copy over the node_modules directory to avoid having npm in the production image.
The problem is that I need to run my Jest test suite from this final Docker image, but since npm isn’t available, I can’t use the usual npm test command. When I try to execute my shell script that contains npm commands, I get an error saying the command isn’t found.
Is there a way to execute Jest tests directly without relying on npm commands? Maybe through some other approach or by calling Jest executable directly?
for sure! just call jest directly with ./node_modules/.bin/jest in your docker image. you can also add node_modules/.bin to your PATH in the dockerfile. it works fine without needing npm!
Try npx jest instead of npm test - it should work in production if you copied node_modules correctly. You could also modify your package.json scripts to use direct binary calls, then run node -e "require('./package.json').scripts.test" but that’s messy. The most reliable way I’ve found is creating a simple shell script that calls the jest binary directly with your config file. Don’t forget to copy your jest.config.js (or whatever config you’re using) to the final stage - Jest needs it to run.
Here’s another trick that works great - set up an alias in your Dockerfile. Just add RUN echo 'alias jest="./node_modules/.bin/jest"' >> ~/.bashrc to your final stage. Now you can use the jest command directly instead of typing out the full path every time. I’ve been doing this in production for months with zero problems. Just make sure your working directory’s set right, or the relative path to node_modules won’t work. You could also create a simple wrapper script that handles path resolution automatically - write a quick bash script that calls the jest binary with the right arguments and stick it in your PATH.