如何在cypress中生成随机字符串(指定长度)? cy.request() 中需要传递两个参数

问题描述 投票:0回答:1

我需要在 POST 请求中传递两个应该随机生成的参数 标题和描述 我尝试使用 Cypress._.random(0, 1e6) 但没有运气,因为它只生成了几个数字 标题字段的要求为:5-20 个字母数字字符 描述字段需要:20-200 个字母数字字符


it('should PAA', () => {

        const uuid = () => Cypress._.random(0, 1e6)
        const title = uuid()
        const description = uuid()
        cy.getLocalStorage("accessToken").should("exist");
        cy.getLocalStorage("accessToken").then(token => {
        cy.request({
            method : 'POST',
            url: 'myURL',
            headers : {"Authorization": "Bearer " + token},
            body: {
              "extra_fields":{
                  "price":5000,
                  "price_type":"price"
              },
              "area":0,
              "type":"general",
              "user_external_id":"0926c075-6afb-4d66-ba17-8a01a6a93e70",
              "purpose":"for-sale",
              "state":"pending",
              "source":"strat",
              "contact_info":{
                  "name":"Muhammad Haris BH",
                  "mobile":"+923234077603",
                  "roles":[
                    "allow_chat_communication",
                    "show_phone_number"
                  ]
              },
              "title": title,
              "description":description,
              "photos":[
                  
              ],
              "location_id":"2-51",
              "category_id":"249"
            }
          }).then( (response) =>{
            expect(`Response.status = ${response.status}`).to.eq('Response.status = 201')
          })
        });
      });

我在正文中传递标题和描述,但 UUID 只生成几个数字字符 我需要传递至少 20 个字符的字母数字字符串。

random automation cypress
1个回答
1
投票

这个问题Generate random string/characters in JavaScript有你所需要的。

但是对于额外的随机维度,请随机化验证最小值和最大值之间的长度。

function makeStringOfLength({min, max}) {

  const length = Math.random() * (max - min + 1) + min
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  let result = '';

  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }

  return result;
}

const title = makeStringOfLength({min:5, max:20})
const description = makeStringOfLength({min:20, max:200})
© www.soinside.com 2019 - 2024. All rights reserved.