Unable to get Second Lab in Jenkins Pipeline to work

I am on the Kubernetes and GitOps module in the Jenkins Pipelines course and I have hit a wall on the second lab.
The first problem is that you MUST do an npm audit fix before anything else as the NPM audit step in the pipleline will fail.
The second problem is that my Jenkinsfile, even though it resembles the solution, the when block is not properly skipping the two new steps. In a previous attempt at this same lab, when I was attempting the pull request it WAS skipping those steps. Based on AI and also google search, I replaced the block

when {
    branch 'PR*'
}

with

when {
   changeRequest()
|

In both cases, the above two blocks will still execute the stage even for just an update to the feature branch. It is as if the when block is doing the exact opposite of what it is supposed to do.

Here is a copy of the Jenkns file:

pipeline {
    agent any

    tools {
        nodejs 'nodejs-22-6-0'
    }

    environment {
        MONGO_URI = 'mongodb+srv://supercluster.d83jj.mongodb.net/superData'
        MONGO_USERNAME = credentials('mongo-db-username')
        MONGO_PASSWORD = credentials('mongo-db-password')
  	    GITEA_TOKEN = credentials('gitea-api-token')
    }

    stages {
        stage('Install Dependencies') {
            steps {
                sh 'npm install --no-audit'
            }
        }

        stage('NPM Dependency Audit') {
            steps {
                sh 'npm audit --audit-level=critical'
            }
        }

        stage('Unit Testing') {
            steps {
                sh 'npm test'
            }
        }

        stage('Code Coverage') {
            steps {
                catchError(buildResult: 'SUCCESS', message: 'Oops! it will be fixed in future releases', stageResult: 'UNSTABLE') {
                    sh 'npm run coverage'
                }
            }
        }

        stage('Build Docker Image') {
            steps {
                script {
                    sh 'docker build -t kodekloud-hub:5000/solar-system:${GIT_COMMIT} .'
                }
            }
        }

        stage('Trivy Scan') {
            steps {
                script {
                    sh '''
                    trivy image kodekloud-hub:5000/solar-system:${GIT_COMMIT} \
                    --severity CRITICAL \
                    --exit-code 1 \
                    --format json -o trivy-image-CRITICAL-results.json
                    '''
                }
            }
        }

        stage('Publish Image - DockerHub') {
            steps {
                script {
                    withDockerRegistry([credentialsId: 'docker-hub-credentials', url: 'http://kodekloud-hub:5000']) {
                        sh 'docker push kodekloud-hub:5000/solar-system:$GIT_COMMIT'
                    }
                }
            }
        }

        stage('Localstack - AWS S3') {
            steps {
                withAWS(credentials: 'localstack-aws-credentials', endpointUrl: 'http://localhost:4566', region: 'us-east-1') {
                    sh '''
                    ls -ltr
                    mkdir reports-$BUILD_ID
                    cp -rf coverage/ reports-$BUILD_ID/
                    cp test-results.xml trivy*.* reports-$BUILD_ID/
                    ls -ltr reports-$BUILD_ID/
                    '''
                    s3Upload(
                        file: "reports-$BUILD_ID", 
                        bucket: 'solar-system-jenkins-reports-bucket', 
                        path: "jenkins-$BUILD_ID/",
                        pathStyleAccessEnabled: true
                    )
                }
            }
        }

        stage('Deploy to VM') {
            when {
                expression { return env.GIT_BRANCH ==~ /feature\/.*/ }
            }
            steps {
                script {
                    sshagent(credentials: ['vm-dev-deploy-instance']) {
                        sh '''
                        ssh -o StrictHostKeyChecking=no root@node01 "
                        if sudo docker ps -a | grep -q 'solar-system'; then
                            echo 'Container found. Stopping...'
                            sudo docker stop 'solar-system' && sudo docker rm 'solar-system'
                            echo 'Container stopped and removed.'
                        fi
                        sudo docker run --name solar-system \
                        -e MONGO_URI=$MONGO_URI \
                        -e MONGO_USERNAME=$MONGO_USERNAME \
                        -e MONGO_PASSWORD=$MONGO_PASSWORD \
                        -p 3000:3000 -d kodekloud-hub:5000/solar-system:$GIT_COMMIT
                        "
                        '''
                    }
                }
            }
        }

        stage('Integration Testing - VM') {
            when {
                expression { return env.GIT_BRANCH ==~ /feature\/.*/ }
            }
            steps {
                sh 'bash dev-integration-test-vm.sh'
            }
        }

	stage('Update and Commit Image Tag') {
      steps {
        when  {
                changeRequest()
        }
        sh 'git clone -b main https://5555-port-mgof5rk5mt2dsfyv.labs.kodekloud.com/dasher-org/solar-system-gitops-argocd'
        dir("solar-system-gitops-argocd/kubernetes") {
          sh '''
            git checkout main
            git checkout -b feature-$BUILD_ID
            sed -i "s#kodekloud:5000.*#kodekloud-hub:5000/solar-system:$GIT_COMMIT#g" deployment.yml
            cat deployment.yml
            git config user.name "Jenkins CI"
            git config --global user.email "[email protected]"
            git remote set-url origin http://[email protected]//dasher-org/solar-system-gitops-argocd
            git add .
            git commit -am "Updated docker image"
            git push -u origin feature-$BUILD_ID
          '''
        }
      }
    }


    stage('Kubernetes Deployment - Raise PR') {
      when  {
                changeRequest()
            }
      steps {
        sh """
          curl -X 'POST' \
            'https://5555-port-mgof5rk5mt2dsfyv.labs.kodekloud.com/api/v1/repos/dasher-org/solar-system-gitops-argocd/pulls' \
            -H 'accept: application/json' \
            -H 'Authorization: token $GITEA_TOKEN' \
            -H 'Content-Type: application/json' \
            -d '{
            "assignee": "gitea-admin",
            "assignees": [
              "gitea-admin"
            ],
            "base": "main",
            "body": "Updated docker image in deployment manifest",
            "head": "feature-$BUILD_ID",
            "title": "Updated Docker Image"
          }'
        """
      }
    }
    }
    post {
        always {
            script {
                if (fileExists('solar-system-gitops-argocd')) {
                    sh 'rm -rf solar-system-gitops-argocd'
                }
            }
            junit allowEmptyResults: true, stdioRetention: '', testResults: 'test-results.xml'
            publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'coverage/lcov-report', reportFiles: 'index.html', reportName: 'Code Coverage HTML Report', reportTitles: '', useWrapperFileDirectly: true])
            sh 'trivy convert --format template --template "/usr/local/share/trivy/templates/html.tpl" --output trivy-image-CRITICAL-results.html trivy-image-CRITICAL-results.json'
            publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: "./", reportFiles: "trivy-image-CRITICAL-results.html", reportName: "Trivy Image Critical Vul Report", reportTitles: "", useWrapperFileDirectly: true])
        }
    }
}

This is my 3rd time trying to get this lab done!

First, here is a link to the lab for KK support:
https://learn.kodekloud.com/user/courses/jenkins-pipelines/module/fb6b2c83-178c-4962-b4e6-ca5528721170/lesson/dce22250-2697-4574-9476-0486e26ee983

I did find one error in the Jenkins file to do with the placement of the while{} directive, but am now struggling to figure out why when I open the PR, it doesn’t trigger Jenkins AT ALL.

Here is the Jenkinsfile:

pipeline {
    agent any

    tools {
        nodejs 'nodejs-22-6-0'
    }

    environment {
        MONGO_URI = 'mongodb+srv://supercluster.d83jj.mongodb.net/superData'
        MONGO_USERNAME = credentials('mongo-db-username')
        MONGO_PASSWORD = credentials('mongo-db-password')
        GITEA_TOKEN = credentials('gitea-api-token')
    }

    stages {
        stage('Install Dependencies') {
            steps {
                sh 'npm install --no-audit'
            }
        }

        stage('NPM Dependency Audit') {
            steps {
                sh 'npm audit --audit-level=critical'
            }
        }

        stage('Unit Testing') {
            steps {
                sh 'npm test'
            }
        }

        stage('Code Coverage') {
            steps {
                catchError(buildResult: 'SUCCESS', message: 'Oops! it will be fixed in future releases', stageResult: 'UNSTABLE') {
                    sh 'npm run coverage'
                }
            }
        }

        stage('Build Docker Image') {
            steps {
                script {
                    sh 'docker build -t kodekloud-hub:5000/solar-system:${GIT_COMMIT} .'
                }
            }
        }

        stage('Trivy Scan') {
            steps {
                script {
                    sh '''
                    trivy image kodekloud-hub:5000/solar-system:${GIT_COMMIT} \
                    --severity CRITICAL \
                    --exit-code 1 \
                    --format json -o trivy-image-CRITICAL-results.json
                    '''
                }
            }
        }

        stage('Publish Image - DockerHub') {
            steps {
                script {
                    withDockerRegistry([credentialsId: 'docker-hub-credentials', url: 'http://kodekloud-hub:5000']) {
                        sh 'docker push kodekloud-hub:5000/solar-system:$GIT_COMMIT'
                    }
                }
            }
        }

        stage('Localstack - AWS S3') {
            steps {
                withAWS(credentials: 'localstack-aws-credentials', endpointUrl: 'http://localhost:4566', region: 'us-east-1') {
                    sh '''
                    ls -ltr
                    mkdir reports-$BUILD_ID
                    cp -rf coverage/ reports-$BUILD_ID/
                    cp test-results.xml trivy*.* reports-$BUILD_ID/
                    ls -ltr reports-$BUILD_ID/
                    '''
                    s3Upload(
                        file: "reports-$BUILD_ID", 
                        bucket: 'solar-system-jenkins-reports-bucket', 
                        path: "jenkins-$BUILD_ID/",
                        pathStyleAccessEnabled: true
                    )
                }
            }
        }

        stage('Deploy to VM') {
            when {
                expression { return env.GIT_BRANCH ==~ /feature\/.*/ }
            }
            steps {
                script {
                    sshagent(credentials: ['vm-dev-deploy-instance']) {
                        sh '''
                        ssh -o StrictHostKeyChecking=no root@node01 "
                        if sudo docker ps -a | grep -q 'solar-system'; then
                            echo 'Container found. Stopping...'
                            sudo docker stop 'solar-system' && sudo docker rm 'solar-system'
                            echo 'Container stopped and removed.'
                        fi
                        sudo docker run --name solar-system \
                        -e MONGO_URI=$MONGO_URI \
                        -e MONGO_USERNAME=$MONGO_USERNAME \
                        -e MONGO_PASSWORD=$MONGO_PASSWORD \
                        -p 3000:3000 -d kodekloud-hub:5000/solar-system:$GIT_COMMIT
                        "
                        '''
                    }
                }
            }
        }

        stage('Integration Testing - VM') {
            when {
                expression { return env.GIT_BRANCH ==~ /feature\/.*/ }
            }
            steps {
                sh 'bash dev-integration-test-vm.sh'
            }
        }
        stage('Update and Commit Image Tag') {
            when  {
                branch 'PR*'
            }
            steps {
                sh 'git clone -b main https://5555-port-oxw7vvdeqwpopvb3.labs.kodekloud.com/dasher-org/solar-system-gitops-argocd'
                dir("solar-system-gitops-argocd/kubernetes") {
                  sh '''
                    git checkout main
                    git checkout -b feature-$BUILD_ID
                    sed -i "s#kodekloud:5000.*#kodekloud:5000/solar-system:$GIT_COMMIT#g" deployment.yml
                    cat deployment.yml
                    git config user.name "Jenkins CI"
                    git config --global user.email "[email protected]"
                    git remote set-url origin http://[email protected]/dasher-org/solar-system-gitops-argocd
                    git add .
                    git commit -am "Updated docker image"
                    git push -u origin feature-$BUILD_ID
                  '''
                }
            }
        }


        stage('Kubernetes Deployment - Raise PR') {
            when  {
                branch 'PR*'
            }
            steps {
                sh """
                  curl -X 'POST' \
                    'https://5555-port-oxw7vvdeqwpopvb3.labs.kodekloud.com//api/v1/repos/dasher-org/solar-system-gitops-argocd/pulls' \
                    -H 'accept: application/json' \
                    -H 'Authorization: token $GITEA_TOKEN' \
                    -H 'Content-Type: application/json' \
                    -d '{
                    "assignee": "gitea-admin",
                    "assignees": [
                      "gitea-admin"
                    ],
                    "base": "main",
                    "body": "Updated docker image in deployment manifest",
                    "head": "feature-$BUILD_ID",
                    "title": "Updated Docker Image"
                  }'
                """
            }
        }
    }
    post {
        always {
            script {
                if (fileExists('solar-system-gitops-argocd')) {
                    sh 'rm -rf solar-system-gitops-argocd'
                }
            }
            junit allowEmptyResults: true, stdioRetention: '', testResults: 'test-results.xml'
            publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'coverage/lcov-report', reportFiles: 'index.html', reportName: 'Code Coverage HTML Report', reportTitles: '', useWrapperFileDirectly: true])
            sh 'trivy convert --format template --template "/usr/local/share/trivy/templates/html.tpl" --output trivy-image-CRITICAL-results.html trivy-image-CRITICAL-results.json'
            publishHTML([allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: "./", reportFiles: "trivy-image-CRITICAL-results.html", reportName: "Trivy Image Critical Vul Report", reportTitles: "", useWrapperFileDirectly: true])
        }
    }
}

The only thing about this PR that may be different is you MUST do some sort of NPM audit fix because as of 2025, 2 NPM packages are flagged as critical. In my PR, I have 4 files being updated instead of the expected 1 due to the NPM audit fix I needed to do:

I added a .gitignore so that it would not load node_modules from my local copy of the project.
The PR is created and it shows some checks being pending - the Jenkins pipeline it highlights is actually the build that happened just after I committed to feature branch which correctly skipped the docker and kubernetes stages, but it appears that it is waiting on something else before it triggers Jenkins again.

Can someone PLEASE explain WHAT HAVE I MISSED???

I found what I was missing. I was looking on the specific branch in Jenkins, whereas from the solar-system level, you would see branches AND pull requests. I was looking in the branches areas. I did see pull requests once I looked in the right place.