Cypress验证下拉框选项遇option不可迭代及undefined错误求助
解决Cypress下拉选项验证的“option不可迭代”及[undefined]问题
问题场景
验证含4个选项的下拉框时,执行以下代码出现**“option不可迭代”**错误:
it('Verify the value of Request Type drop down', function() { cy.get('#MailForm > div:nth-child(6) > select').find('option').then(option => { const actual = [...option].map(o => o.value) expect(actual).to.deep.eq(["Sales Request"]) }) })
若将扩展运算符移除,改为const actual = [option].map(o => o.value),则返回**数组[undefined]**错误。对应下拉框HTML结构如下:
<select name="request_type" required="required" class="form-control"><option value="">Select Request Type</option> <option value="Sales Lead">Sales Lead</option> <option value="Add Insurance">Add Insurance</option> <option value="Price Match">Price Match</option></select>
原因分析
Cypress通过.find('option')获取的option是jQuery对象集合,并非原生JavaScript数组:
- 直接用扩展运算符
[...option]解构会报错,因为jQuery对象不支持迭代协议; - 把jQuery对象放进数组
[option]后,map遍历的是这个jQuery对象本身,而非内部的DOM元素,自然取不到value,返回undefined。
解决方案
方法1:将jQuery对象转为原生DOM数组
使用jQuery的.toArray()方法把集合转为原生DOM元素数组,再进行map操作:
it('Verify the value of Request Type drop down', function() { cy.get('#MailForm > div:nth-child(6) > select').find('option').then($options => { const actual = $options.toArray().map(o => o.value); // 注意:预期数组要和HTML实际选项值对应 expect(actual).to.deep.eq(["", "Sales Lead", "Add Insurance", "Price Match"]); }); });
方法2:使用Cypress.invoke调用jQuery map方法
更贴合Cypress风格的写法,直接调用jQuery的map方法提取值:
it('Verify the value of Request Type drop down', function() { cy.get('#MailForm > div:nth-child(6) > select') .find('option') .invoke('map', function() { return this.value; // 此处this指向单个option DOM元素 }) .then(actual => { expect(actual).to.deep.eq(["", "Sales Lead", "Add Insurance", "Price Match"]); }); });
注意:原代码中的预期数组
["Sales Request"]与HTML实际选项不符,需修正为对应的值集合。
内容的提问来源于stack exchange,提问作者VinodPatel
相关产品推荐
相关产品推荐

