简体   繁体   English

在 Cypress 中创建一个随机字符串并将其传递给 cy 命令

[英]Creating a random string in Cypress and passing this to a cy command

I am new to Cypress and have a small problem which I would like some help on.我是 Cypress 的新手,有一个小问题,我需要一些帮助。

I have an input field in my application which allows me to enter a name.我的应用程序中有一个输入字段,允许我输入名称。 This name has to be unique and must not be the same as an existing name already in the system.此名称必须是唯一的,并且不得与系统中已有的名称相同。

I am currently clicking this input field by:我目前正在通过以下方式单击此输入字段:
cy.get('input[type="text"].form-control')

If I use the cy.type() command, this will always type in the same value provided, but each time the test runs, I want to assign a different value.如果我使用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

Expected预期的
Create a function that allows a random string to be generated and then, for that to be typed into the input field by a normal cypress command.创建一个允许生成随机字符串的函数,然后通过普通的 cypress 命令将其输入到输入字段中。

I just found another approach in a blog, adding it here for reference.刚刚在博客中找到了另一种方法,添加在这里以供参考。

const uuid = () => Cypress._.random(0, 1e6)
const id = uuid()
const testname = `testname${id}`
cy.get('input').type(testname);

worked well for me :)对我来说效果很好:)

Try this code.Hope This will work.试试这个代码。希望这会奏效。

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;
  }

OR Use the following code或使用以下代码

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;
  }

Given you need less than 1 id per millisecond, you don't need unique values in parallel environments, and you are not a time traveller, you may use Date.now() .鉴于您每毫秒需要少于 1 个 id,您在并行环境中不需要唯一值,并且您不是时间旅行者,您可以使用Date.now()

If you need more than 1 id per millisecond, you may use Date.now() as a seed for Cypress._.uniqueId() :如果每毫秒需要超过 1 个 id,您可以使用Date.now()作为Cypress._.uniqueId() Date.now()的种子:

const uniqueSeed = Date.now().toString();
const getUniqueId = () => Cypress._.uniqueId(uniqueSeed);

it('uses a unique id', () => {
  const uniqueId = getUniqueId();
});

I am making some assumptions here.我在这里做一些假设。 I assume there is some sort of API that you call to check if there is a duplicate name.我假设您调用某种 API 来检查是否有重复的名称。 I would stub/mock that to get around it.我会存根/嘲笑它来解决它。 I am taking a guess here, but you pass down the name and you get something back that says true or false, you stub that to always return false, so you can do your duplicate.我在这里猜测一下,但是你传递了名字,你会得到一些说真或假的东西,你存根总是返回假,所以你可以做你的重复。

I created a single function that generates the random string, then create a variable to store this value and then use the value within the logic of the rest of the test.我创建了一个生成随机字符串的函数,然后创建一个变量来存储该值,然后在其余测试的逻辑中使用该值。

    function generate_random_string(string_length) {
        let random_string = '';
        let random_ascii;
        for(let i = 0; i < string_length; i++) {
            random_ascii = Math.floor((Math.random() * 25) + 97);
            random_string += String.fromCharCode(random_ascii)
        }
        return random_string
    }

I then assign this to a variable below:然后我将它分配给下面的一个变量:

var random_string = generate_random_string(8)

Then the extracted output from that and put into the field by using the simple get and type commands in Cypress:然后使用 Cypress 中的简单gettype命令从中提取输出并放入该字段:

cy.get('input[type="text"].form-control').type(random_string)

This gets the value and types it into the field that I wanted.这将获取值并将其键入到我想要的字段中。 I can also "random_string" again in any test, say for example if I wish to do some assertions later on in the test.我还可以在任何测试中再次“随机字符串”,例如,如果我希望稍后在测试中做一些断言。

example.spec.js

it('timestamp', function() {
cy.task('datenow').then((random) => { cy.log('test' + random)})
}) 

plugins/index.js

on('task', {
datenow () {
return Date.now()
}
}) 

The above code will generate random strings上面的代码会生成随机字符串

There is a better way of doing that.有一种更好的方法可以做到这一点。 Check this link for the complete package details.检查此链接以获取完整的包详细信息。 https://www.npmjs.com/package/faker https://www.npmjs.com/package/faker

First add the Faker library by running the following npm command.首先通过运行以下 npm 命令添加 Faker 库。

npm install faker

Next call the relevant faker data generation commands wherever data is inputed to the system by your Cypress automated test.接下来,在 Cypress 自动化测试将数据输入系统的任何位置调用相关的伪造数据生成命令。

const faker = require("faker");
cy.get('input').type(faker.random.alphaNumeric());

暂无
暂无

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

相关问题 在 Cypress 中覆盖 cy.click() 命令的正确方法是什么? - What is the proper way to overwrite the cy.click() command in Cypress? 如何通过覆盖赛普拉斯中的 cy.type() 命令来清除()输入字段 - How to clear() input fields by overwriting cy.type() command in Cypress 带有 cy.request 的 Cypress 登录命令导致后续 cy.visit 失败 - Cypress login command with cy.request causes subsequent cy.visit to fail 无法在cypress命令cy.get()中设置变量值以在命令外部使用 - Cannot set a variable's value inside cypress command cy.get() to use outside the command 将相同的随机数传递给赛普拉斯的所有测试 - Passing a same random number to all tests in Cypress 与 cypress 中的 cy.log 混淆 - confused with cy.log in cypress CypressError:Cypress 检测到您从命令返回了 promise,同时还在该 promise 中调用了一个或多个 cy 命令 - CypressError: Cypress detected that you returned a promise from a command while also invoking one or more cy commands in that promise command.js 中随机生成的字符串 function 在 e2e loginTest.js 中未得到识别 - 赛普拉斯 - random generated string function in command.js is not getting recognized in e2e loginTest.js - Cypress cy.type() 只能接受字符串或数字。 你传入:未定义的柏树错误 - cy.type() can only accept a string or number. You passed in: undefined cypress error 创建用于在 typescript 中获取文本的 cypress 自定义命令 - Creating a cypress custom command for getting text in typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM