cypress - 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.
解决方案
这应该有效:
// 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)
推荐阅读
- c# - Visual Studio Asp WebForms 名称不存在
- c - 为什么我的 C 程序不打印 if 语句的输出?
- css - flexbox 列中的图像无法在 Chrome 中正确呈现
- c# - 如何将字符串从一个项目的应用程序域传递到另一个项目的应用程序域
- angular - ionic 4 在键盘上方显示页脚
- regex - 用记事本++中的一个替换最后2个字符
- php - Wordpress single.php 另一个 get_post 函数破坏了第一个函数
- java - Apache Crunch 无法写入输出
- json - 检查特定 JSON 键的重复值
- flask - “Fieldlist”/“FormField”无法使用 flask_wtf 正确渲染