首页 > 解决方案 > Use generated string in another field

问题描述

I have several fields on a web page. The first two fields require a unique string to be entered every time the test suite is run. I have code that generates a random string in the first 'Name' field. I want to copy whatever string is generated into the second 'Label' field, so they both match.

I have tried using a copy function, but this doesn't seem to work correctly in Cypress. I also tried logging the value created in the generation function, then using that logged value in the next test. But that didn't work either. I'm not sure if there is a way around this?

Code to generate the random string in the first field:

cy.get('#Name')
        .should('exist')

        .type(Name_Alpha_Numeric())
            // Enter random string
            function Name_Alpha_Numeric() {
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                for (var i = 0; i < 10; i++)
                text += possible.charAt(Math.floor(Math.random() * possible.length));

                return text;
            }

Hoping there is a very straightforward solution to this.

标签: cypress

解决方案


这应该有效:

// 0. write the function
function Name_Alpha_Numeric() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 10; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

// 1. generate the string and store it in a variable
const randomName = Name_Alpha_Numeric()

// 2. type it in
cy.get('#Name').type(randomName)

// 3. verify that #Label also has this text
cy.get('#Label').should('have.text', randomName)

推荐阅读