Cypress中从Fixture获取数组并添加默认项后与页面数组对比问题
Cypress数组对比问题解决方案
问题场景
我刚接触Cypress,遇到数组对比问题。fixtures目录下的TestData.json结构如下:
{ "data1": { "Client": "Client1", "ClientID": "202300001", "PlanTypes": ["type1", "type2"] }, "data2": { "Client": "Client2", "ClientID": "202300001", "PlanTypes": ["type3", "type4", "type5"] } }
页面下拉列表包含默认项""和"For Validation",以及随客户端变化的动态项(比如type1、type2)。我已将下拉项存入数组arr1,但在将Fixture中的PlanTypes数组添加默认项后与arr1对比时出错。
原代码
script.js
import filePage from "../../../support/page-objects/filePage"; const filePage = new filePage() const testDataFile = '/TestData.json' cy.fixture(testDataFile).then((testData) => { const msTestData = testData.data1 filePage.checkPlanTypes(msTestData); });
filePage.js
checkPlanTypes(msTestData) { let arr1 = [] this.elements.dataPlanTypeList().find('li').each((planTypeData) => { arr1.push(planTypeData.text().trim()) }).then(() => { let clientPlanTypes = [] clientPlanTypes.push("") clientPlanTypes.push(msTestData) clientPlanTypes.push("For Validation") expect(clientPlanTypes).to.have.same.members(arr1) }) }
错误原因
- 数据取值错误:
clientPlanTypes.push(msTestData)是将整个data1对象推入数组,而非取其中的PlanTypes数组。 - 数组嵌套问题:直接push数组会把
PlanTypes作为单个元素存入clientPlanTypes,导致数组嵌套(比如["", ["type1","type2"], "For Validation"]),但页面的arr1是平级数组(比如["", "type1", "type2", "For Validation"]),二者结构、长度不匹配。
修正方案
基础修正版(filePage.js)
checkPlanTypes(msTestData) { let arr1 = [] this.elements.dataPlanTypeList().find('li').each((planTypeData) => { arr1.push(planTypeData.text().trim()) }).then(() => { // 用扩展运算符展开PlanTypes数组,避免嵌套 const clientPlanTypes = [ "", ...msTestData.PlanTypes, "For Validation" ] // 忽略顺序校验元素一致性,适合下拉项顺序不固定的场景 expect(clientPlanTypes).to.have.same.members(arr1) // 如果下拉项顺序固定,可改用严格匹配: // expect(arr1).to.deep.equal(clientPlanTypes) }) }
代码优化版
可以直接传入PlanTypes数组减少层级,让代码更简洁:
script.js
import filePage from "../../../support/page-objects/filePage"; const filePage = new filePage() const testDataFile = '/TestData.json' cy.fixture(testDataFile).then((testData) => { // 直接传入PlanTypes数组 filePage.checkPlanTypes(testData.data1.PlanTypes); });
filePage.js
checkPlanTypes(planTypes) { let arr1 = [] this.elements.dataPlanTypeList().find('li').each((planTypeData) => { arr1.push(planTypeData.text().trim()) }).then(() => { const clientPlanTypes = [ "", ...planTypes, "For Validation" ] expect(clientPlanTypes).to.have.same.members(arr1) }) }
内容的提问来源于stack exchange,提问作者Jm2323
相关产品推荐
相关产品推荐

