Cypress函数中无法用arg3引用JSON数组,求解决方法
问题:Cypress测试函数无法通过参数引用Fixture中的数组
我编写了如下Cypress测试函数checkEvents,期望通过参数arg3引用Notification_Events.json文件中的对应数组,但尝试直接使用arg3或$arg3均无法生效,请问该如何解决?
代码如下:
function checkEvents(arg1,arg2,arg3){ // arg1 = categories drop down button // arg2 = Number of events in category // arg3 = Name of category allure.step("Valid events in "+ arg1 + "", () => { // Open dropdown cy.get('span.material-icons').eq(arg1).click() // Count number of options within the category (24) cy.get('.innerCol tr td.mat-column-name').should('have.length', arg2) // Validate events in each category cy.fixture('Notification_Events.json').then(function(testdata) { this.testdata = testdata cy.get('.innerCol tr td.mat-column-name').each(($ele, i) => { expect($ele).to.have.text(this.testdata.arg3[i]) }) }) // Close the Dropdown cy.get('span.material-icons').eq(arg1).click() cy.wait(1000) }) // End of Allure Step } // End of Function // Uses checkEvents function to check contents of event categories checkEvents("0","45","Fault") checkEvents("1","36","Warning")
解决方案
1. 核心问题:动态访问对象属性的语法错误
在JavaScript中,使用.访问对象属性时,属性名是固定的字符串;如果要通过变量动态指定属性名,必须使用方括号语法对象[变量名]。
原代码中this.testdata.arg3[i]的写法会去查找testdata中名为arg3的属性,而不是变量arg3的值(比如"Fault"或"Warning")对应的属性,这就是导致失败的原因。
2. 修改后的关键代码
将验证逻辑中的属性访问方式改为方括号语法:
cy.fixture('Notification_Events.json').then(function(testdata) { cy.get('.innerCol tr td.mat-column-name').each(($ele, i) => { // 用方括号通过变量arg3动态获取对应数组 expect($ele).to.have.text(testdata[arg3][i]) }) })
3. 额外优化:修复异步执行时序问题
原代码中关闭下拉菜单的操作在cy.fixture回调之外,会因为Cypress的异步特性导致下拉菜单提前关闭(验证逻辑还没执行完)。建议将关闭操作移到验证完成后的回调中:
function checkEvents(arg1,arg2,arg3){ // arg1 = categories drop down button // arg2 = Number of events in category // arg3 = Name of category allure.step("Valid events in "+ arg1 + "", () => { // Open dropdown cy.get('span.material-icons').eq(arg1).click() // Count number of options within the category (24) cy.get('.innerCol tr td.mat-column-name').should('have.length', arg2) // Validate events in each category cy.fixture('Notification_Events.json').then(function(testdata) { cy.get('.innerCol tr td.mat-column-name').each(($ele, i) => { expect($ele).to.have.text(testdata[arg3][i]) }).then(() => { // 验证完成后再关闭下拉菜单 cy.get('span.material-icons').eq(arg1).click() cy.wait(1000) }) }) }) // End of Allure Step } // End of Function // Uses checkEvents function to check contents of event categories checkEvents("0","45","Fault") checkEvents("1","36","Warning")
这样可以确保验证逻辑完全执行后再关闭下拉菜单,避免异步时序问题导致的测试失败。
内容的提问来源于stack exchange,提问作者Jessa Brandy
相关产品推荐
相关产品推荐

