March 16, 2025

ikayaniaamirshahzad@gmail.com

Integrating Cypress with Jenkins API for Automated Test Preparation


When performing automated tests in Cypress (or any automation tool), you often need to prepare data or bring the application to a certain state before execution. This can involve seeding a database, generating test data, or performing backend tasks.

A common challenge in test automation is executing backend tasks before running tests. Traditionally, these tasks were triggered manually, preventing full test automation. However, integrating Jenkins API with Cypress allows us to programmatically launch Jenkins jobs, making the process seamless and fully automated.



Automating Pre-Test Jobs with Jenkins API

To incorporate Jenkins jobs into Cypress, we use the Jenkins API to start a job and wait for its completion. Let’s define some custom Cypress commands to handle this.



Starting a Jenkins Job

We begin by defining a general function to start a Jenkins job:

const JENKINS_URL = '{your_jenkins_url}';
const JOB_NAME = 'Console script runner (dev-beta)'; // Define your job
const API_TOKEN = '{your_jenkins_api_token}';

function startJenkinsJob(project, script, wait) {
    cy.task('log', `Starting Jenkins job: ${script}`);
    const url = `${JENKINS_URL}/job/${JOB_NAME}/buildWithParameters?token=${API_TOKEN}&PROJECT=${project}&ENVIRONMENT=beta&CONSOLE_SCRIPT=${script}`;

    cy.request({
        method: 'GET',
        url: url,
        failOnStatusCode: false,
    }).then((response) => {
        if (wait) {
            const locationParts = response.headers.location.split('/');
            const queueId = locationParts.slice(-2, -1)[0];
            cy.waitForBuildNumber(queueId);
        }
    });
}
Enter fullscreen mode

Exit fullscreen mode

This function sends a request to Jenkins to start a job and retrieves a queue ID. Since jobs are queued before execution, we need to monitor the queue status. The actual job parameters (in this case project and environment) may differ based on your Jenkins configuration.



Waiting for jobs in queue

Next, we create a Cypress command to check the queue status:

Cypress.Commands.add('waitForBuildNumber', (queueId) => {
    cy.getQueueItemStatus(queueId).then((res) => {
        if (res.body.executable) {
            const buildNumber = res.body.executable.number;
            cy.task('log', `Job started with Build Number: ${buildNumber}`);
            cy.waitForJobCompletion(buildNumber);
        } else {
            cy.wait(3000); // Retry after 3 seconds
            cy.waitForBuildNumber(queueId);
        }
    });
});
Enter fullscreen mode

Exit fullscreen mode

This command checks if the job has moved out of the queue and received a build number. If not, it retries after a short delay.



Monitoring Job Completion

Once a job is assigned a build number, we can track its execution status:

Cypress.Commands.add('waitForJobCompletion', (buildNumber) => {
    cy.request({
        method: 'GET',
        url: `${JENKINS_URL}/job/${encodeURIComponent(JOB_NAME)}/${buildNumber}/api/json`,
        jenkinsAuth,
        failOnStatusCode: false,
    }).then((res) => {
        const result = res.body.result;
        if (result) {
            cy.task('log', `Job completed with status: ${result}`);
        } else {
            cy.wait(3000); // Retry after 3 seconds
            cy.waitForJobCompletion(buildNumber);
        }
    });
});
Enter fullscreen mode

Exit fullscreen mode

This command periodically checks whether the job has completed and logs its status.



Checking Queue Item Status

To get the queue item status, we define another Cypress command:

Cypress.Commands.add('getQueueItemStatus', (queueId) => {
    return cy.request({
        method: 'GET',
        url: `${JENKINS_URL}/queue/item/${queueId}/api/json`,
        jenkinsAuth,
        failOnStatusCode: false,
    });
});
Enter fullscreen mode

Exit fullscreen mode



Implementing Specific Jenkins Commands

With these general functions in place, we can define specific commands. For example, to clear a cache before running tests:

Cypress.Commands.add('clearCache', (country, wait) => {
    return startJenkinsJob('my_project', 'cache/flush-all country=' + country, wait);
});
Enter fullscreen mode

Exit fullscreen mode



Using Jenkins Jobs in Cypress Tests

Now, let’s implement our cache-clearing command in a test:

describe('Test with cleared cache', () => {
    before(() => {
        const countryId = Cypress.env().countryId;
        cy.task('log', 'Clearing cache on ' + countryId);
        cy.clearCache(countryId, true);
    });

    it('Your test...', () => {
        // Your test code
    });
});
Enter fullscreen mode

Exit fullscreen mode



Expanding Possibilities for Automated Testing

Integrating Cypress with Jenkins API opens up many new opportunities:

  • Automatically setting up test environments.
  • Running backend processes before tests.
  • Ensuring data consistency before executing test cases.

With this approach, we eliminate the need for manual job execution, making our test automation more robust and reliable.

What other pre-test tasks would you automate with this method? Let’s discuss in the comments!



Source link

Leave a Comment