Jas*_*Jas 9 javascript e2e-testing cypress
我是 Cypress 的新手,有一个小问题,我需要一些帮助。
我的应用程序中有一个输入字段,允许我输入名称。此名称必须是唯一的,并且不得与系统中已有的名称相同。
我目前正在通过以下方式单击此输入字段:
cy.get('input[type="text"].form-control')
如果我使用该cy.type()命令,这将始终输入所提供的相同值,但每次测试运行时,我都想分配一个不同的值。
// Fill in some details of a new class to proceed with creation
cy.get('.pull-left > h4').contains('Add a new class')
cy.get('input[type="text"].form-control') // Clicks on the field
// Some code to go here to create a random string and use what was created and
type this into the field above
Run Code Online (Sandbox Code Playgroud)
预期
创建一个函数,该函数允许生成一个随机字符串,然后通过普通的 cypress 命令将其输入到输入字段中。
小智 17
刚刚在博客中找到了另一种方法,添加在这里以供参考。
const uuid = () => Cypress._.random(0, 1e6)
const id = uuid()
const testname = `testname${id}`
cy.get('input').type(testname);
Run Code Online (Sandbox Code Playgroud)
对我来说效果很好:)
小智 6
鉴于您每毫秒需要的 id 少于 1 个,您在并行环境中不需要唯一值,并且您不是时间旅行者,您可以使用Date.now().
如果您每毫秒需要超过 1 个 id,您可以使用以下内容Date.now()作为种子Cypress._.uniqueId():
const uniqueSeed = Date.now().toString();
const getUniqueId = () => Cypress._.uniqueId(uniqueSeed);
it('uses a unique id', () => {
const uniqueId = getUniqueId();
});
Run Code Online (Sandbox Code Playgroud)
试试这个代码。希望这会奏效。
cy.get(':nth-child(2) > :nth-child(2) > input').type(userID_Alpha())
function userID_Alpha() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 10; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
Run Code Online (Sandbox Code Playgroud)
或使用以下代码
cy.get(':nth-child(2) > :nth-child(2) > input').type(userID_Alpha_Numeric())
function userID_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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17898 次 |
| 最近记录: |