简体   繁体   中英

Jenkins is not getting the url value passed, it says null

While running my tests in jenkins pipeline, it says you have passed the cy.request() url as null . I have mentioned all of the env variables in jenkins. Could someone please advise what is the problem here?

Error: CypressError: cy.request() requires a url . You did not provide a . You did not provide a url .

my .env file:

CYPRESS_TEST_USERNAME=Test1
CYPRESS_TEST_PASSWORD=BooksTest1234
CYPRESS_BASE_URL=https://my-test-url.com/books/
CYPRESS_API_URL=https://my-test-url.com/api/v1.0/books/

my jenkins file

def channel = '#jenkins-cypress'
def ARTEFACT_DIR=""
pipeline {
  agent any
  stages {
    stage('Clone books-suite') {
        steps {
            dir('books-co') {
                script {
                    checkout([
                        $class: 'GitSCM',
                        branches: [
                            [name: "origin/develop"]
                        ],
                        extensions: [
                            [$class: 'CleanCheckout'],
                            [$class: 'LocalBranch', localBranch: '**'],
                            [$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true, timeout: 10]
                        ],
                        userRemoteConfigs: [[
                            credentialsId: 'fsdf68fs61-esdfsdf56546-92ea-7345bcfsfsdfb3d391',
                            url: 'ssh://git@bitbucket_url_location'
                        ]],
                        doGenerateSubmoduleConfigurations: false,
                        submoduleCfg: []
                    ])
                    ARTEFACT_DIR="${env.WORKSPACE}/artefacts/${BUILD_NUMBER}"
                }
            }
        }
    }
    stage('Run cypress') {
        steps {
            script {
                mattermostSend color: 'good', channel: channel, message: "**STARTING** - Cypress starts (<${env.BUILD_URL}|build ${env.BUILD_NUMBER}>)"
                sh "mkdir -p \"${ARTEFACT_DIR}/videos\""
                sh "mkdir -p \"${ARTEFACT_DIR}/screenshots\""
                def baseUrlConfig="-e CYPRESS_baseUrl=https://my-test-url.com/books/"
                def screenshotsFolderConfig="screenshotsFolder=/artefacts/screenshots"
                def videosFolderConfig="videosFolder=/artefacts/videos"
                def config = "--config ${screenshotsFolderConfig},${videosFolderConfig}"
                def cypressArgs = "run --headless --browser chrome ${config} --project /books-suite"
                sh """
                docker run ${baseUrlConfig} \
                  -v \"${ARTEFACT_DIR}:/artefacts\" \
                  -e CYPRESS_OUTPUT_FILE=\"/artefacts/report.html\" \
                  -e CYPRESS_TEST_USERNAME=\"Test1\" \
                  -e CYPRESS_TEST_PASSWORD=\"BooksTest1234\" \
                  -e CYPRESS_BASE_URL=\"https://my-test-url.com/books/\" \
                  -e CYPRESS_API_URL=\"https://my-test-url.com/api/v1.0/books/\" \
                  
                  cypress:latest \
                    /node_modules/.bin/cypress ${cypressArgs}
                """
                mattermostSend color: 'good', channel: channel, message: "**SUCCESSED** - Cypress CI passed successfully (<${env.BUILD_URL}|build ${env.BUILD_NUMBER}>)"
            }
        }
    }
  }
    post {
        always {
            script {
                USER_ID = get_uid()
                GROUP_ID = get_gid()
                sh """
                    docker run --user ${USER_ID}:${GROUP_ID} \
                      -v \"${ARTEFACT_DIR}:/artefacts\" \
                      -v \"${env.WORKSPACE}/books-co:/books\" \
                      -e JSON_DIR=\"/books/tests/cypress/cucumber-json\" \
                      -e OUTPUT_FILE=\"/artefacts/report.html\" \
                      cypress-books-report:latest
                """
            }
            archiveArtifacts artifacts: "artefacts/${BUILD_NUMBER}/**/*", fingerprint: true

            emailext attachmentsPattern: "artefacts/${BUILD_NUMBER}/**/*",
                body: '${FILE, path="' + "artefacts/${BUILD_NUMBER}/report.html" + '"}',
                mimeType: 'text/html',
                to: 'first.lastman@books.com',
                subject: "Cypress Jenkins Build ${currentBuild.currentResult}: Job ${env.JOB_NAME}"

            sh "rm -Rf artefacts/${BUILD_NUMBER}"

            mattermostSend color: 'good', channel: channel, message: "**SUCCESSED** - Cypress CI report generated (<${env.BUILD_URL}|build ${env.BUILD_NUMBER}>)"
        }
        failure {
            mattermostSend color: 'danger', channel: channel, message: "**FAILED** - cypress CI failed (<${env.BUILD_URL}|build ${env.BUILD_NUMBER}> - <${env.BUILD_URL}console|click here to see the console output>)"
        }
    }
}

def get_uid() {
    node('master') {
        return sh(script: "id -u ${USER}", returnStdout: true).trim()
    }
}

def get_gid() {
    node('master') {
        return sh(script: "id -g ${USER}", returnStdout: true).trim()
    }
}

plugins/index.js:

module.exports = (on, config) => {
    on('file:preprocessor', cucumber()),
        on('before:browser:launch', (browser, launchOptions) => {
            console.log("Print browser name: "+browser.name);

            if (browser.name === 'chrome' || browser.name === 'chrome' && browser.isHeadless) {
                launchOptions.args.push('--disable-features=SameSiteByDefaultCookies') // bypass 401 unauthorised access on chromium-based browsers
                return launchOptions
            }

            if (browser.name === 'chrome') {
                // launch chrome using incognito
                launchOptions.args.push(' --incognito')
                return launchOptions
            }

            if (browser.name === 'chrome' && browser.isHeadless) {
                launchOptions.args.push('--disable-gpu');
                return launchOptions
            }
        });

    config = dotenvPlugin(config)                                                                           
    return config

};

commands.js file

Cypress.Commands.add("loginReq", () => {
  cy.request({
    method: 'POST',
    url: Cypress.env('BASE_URL'), // baseUrl is prepended to url
    form: true, 
    body: {
      loginUsername: Cypress.env('TEST_USERNAME'),
      loginPassword: Cypress.env('TEST_PASSWORD')
    }
  }).then((response)=>{
    console.log("login success: "+response);
  })
});

When you set CYPRESS_BASE_URL , Cypress config will look like:

{
    "baseUrl": "your set base url",
    "env": {

    }
}

You can have a look when you run cypress open and then go to Settings in the opened test runner.

The problem is that Cypress.env() reads variables from env object, where your base url is not set because CYPRESS_BASE_URL sets baseUrl property, not env.baseUrl property.

If you want to set CYPRESS_BASE_URL and access it from your tests, then you have to invoke it with Cypress.config().baseUrl .

However, you don't really need to call (not in your example) Cypress.config().baseUrl because Cypress does that automatically for you, so:

cy
  .visit('/');

really means that Cypress prepends the base url for you. The same goes for cy.request() , so in your example, you can delete it from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM