如何在Cypress中生成指定长度的随机字符串用于POST请求参数
问题描述
需要在POST请求中传入两个随机参数:title和description,但当前用Cypress._.random(0, 1e6)生成的只有数字且长度不达标。字段要求如下:
title:5-20位字母数字混合字符description:20-200位字母数字混合字符
解决方案
自定义一个生成随机字母数字字符串的工具函数,支持指定长度范围,即可满足两个字段的要求。
1. 定义随机字符串生成函数
// 生成指定长度范围的随机字母数字字符串 const generateRandomAlphanumeric = (minLength, maxLength) => { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const length = Cypress._.random(minLength, maxLength); let result = ''; for (let i = 0; i < length; i++) { const randomIndex = Cypress._.random(0, chars.length - 1); result += chars.charAt(randomIndex); } return result; };
2. 生成符合要求的参数
替换原来的uuid函数调用,分别生成title和description:
const title = generateRandomAlphanumeric(5, 20); const description = generateRandomAlphanumeric(20, 200);
修改后的完整测试代码
it('should PAA', () => { // 生成指定长度范围的随机字母数字字符串 const generateRandomAlphanumeric = (minLength, maxLength) => { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const length = Cypress._.random(minLength, maxLength); let result = ''; for (let i = 0; i < length; i++) { const randomIndex = Cypress._.random(0, chars.length - 1); result += chars.charAt(randomIndex); } return result; }; const title = generateRandomAlphanumeric(5, 20); const description = generateRandomAlphanumeric(20, 200); 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).to.eq(201); }); }); });
注:原断言写法冗余,已简化为更规范的expect(response.status).to.eq(201)。
内容的提问来源于stack exchange,提问作者Muhammad Haris
相关产品推荐
相关产品推荐

