Jenkins新手求助:如何通过Jenkinsfile启动Node.js服务并执行Mocha集成测试
Hey there! I totally get where you're stuck—when you start your Node server in the foreground, Jenkins just hangs waiting for it to exit, so it never gets to the Test stage. Let's fix that by running the server in the background, verifying it's ready to accept requests before running your tests, and cleaning up the process afterward.
Here's a revised version of your Jenkinsfile that addresses this:
#!/usr/bin/env groovy pipeline { agent { docker { image 'node' args '-u root' } } stages { stage('Build') { steps { echo 'Installing Dependencies...' sh 'npm install' } } stage('Start Server & Execute Tests') { steps { echo 'Starting application in background...' # Run server in background, redirect logs for debugging sh 'nohup npm start > server.log 2>&1 &' echo 'Waiting for server to be ready...' # Poll until server responds (adjust port/endpoint to match your setup) sh ''' until curl -s http://localhost:3000 > /dev/null; do echo "Waiting 2 seconds for server to initialize..." sleep 2 done ''' echo 'Running integration tests...' sh 'npm test' } post { always { echo 'Cleaning up server process...' # Kill the Node server (ignore error if process isn't found) sh 'pkill -f "node server.js" || true' } } } } }
Key Changes Explained:
- Background Server Launch: The
nohup npm start > server.log 2>&1 &command runs your server in the background.nohupensures it persists even if the shell session ends, and we redirect all output toserver.logso you can debug startup issues later. - Readiness Check: The
untilloop usescurlto repeatedly check if your server's endpoint is responding. This is critical—you don't want to run tests before the server is fully initialized. Adjust the URL/port to match your actual server's listening address (use a health check endpoint if you have one, it's more reliable). - Combined Stage: Merging the "Start" and "Test" stages makes sense because they're tightly coupled—there's no reason to leave the server running idle between stages.
- Guaranteed Cleanup: The
post { always {} }block ensures we kill the server process no matter if tests pass or fail. The|| trueprevents the step from failing if the process wasn't found (just in case startup failed).
Alternative Options:
If you don't want to use curl, you could check if the server's port is in use with commands like ss -tulpn | grep :3000, but verifying the server responds to requests is a better check for integration tests.
You could also use process managers like pm2 or forever to start the server, but that would require installing them as dependencies (via npm install -g pm2), which adds extra steps. The above approach is lightweight and doesn't need additional tools.
Hope this gets your pipeline up and running smoothly!
内容的提问来源于stack exchange,提问作者ShwetaJ

