简体   繁体   English

Jenkins 没有通过 url 值,它说 null

[英]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 .在 jenkins 管道中运行我的测试时,它说您已通过cy.request() url 作为null I have mentioned all of the env variables in jenkins.我已经提到了 jenkins 中的所有环境变量。 Could someone please advise what is the problem here?有人可以告诉这里有什么问题吗?

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

my .env file:我的.env文件:

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我的 jenkins 文件

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:插件/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 commands.js 文件

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:当您设置CYPRESS_BASE_URL时,赛普拉斯配置将如下所示:

{
    "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.你可以看看当你运行cypress open然后 go 在打开的测试运行器中设置。

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.问题是Cypress.env()env object 读取变量,因为CYPRESS_BASE_URL设置的是baseUrl属性,而不是env.baseUrl属性,所以没有设置您的基本 url。

If you want to set CYPRESS_BASE_URL and access it from your tests, then you have to invoke it with Cypress.config().baseUrl .如果要设置CYPRESS_BASE_URL并从测试中访问它,则必须使用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:但是,您实际上并不需要调用(不在您的示例中) Cypress.config().baseUrl因为赛普拉斯会自动为您执行此操作,因此:

cy
  .visit('/');

really means that Cypress prepends the base url for you.确实意味着赛普拉斯为您预先添加了基础 url。 The same goes for cy.request() , so in your example, you can delete it from there. cy.request()也是如此,因此在您的示例中,您可以从那里删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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