[英]cypress how to verify all dropdown items without selecting any item
Below is my html for a dropdown control:下面是我的 html 用于下拉控件:
I want to verify that drop down has following items: ["5","15","30","45"]我想验证下拉菜单是否包含以下项目:["5","15","30","45"]
I have written following piece of code:我编写了以下代码:
value=["5","15","30","45"]
cy.get(seelctor).invoke('val').should('deep.equal', value)
I do not want to select all of these items just want to verify that drop down has them.我不想 select 所有这些项目只是想验证下拉有它们。 Also, My html does not has the value attribute.另外,我的 html 没有 value 属性。 How do i assert based on text??我如何根据文本断言?
Create a fixture file data.json
inside cypress/fixtures
and write:在cypress/fixtures
中创建一个夹具文件data.json
并写入:
{
"dropdownValues": ["5","15","30","45"]
}
Your test will be like:您的测试将类似于:
describe('SO Question', function() {
beforeEach(function() {
//Load Fixture File
cy.fixture('data').then(function(testdata) {
this.testdata = testdata
})
})
it('Iterate dropdown and validate', function() {
cy.get(selector).each(($ele, i) => {
expect($ele).to.have.text(this.testdata.dropdownValues[i])
})
})
})
The values between tags like <li>15</li>
are accessed on individual element with .invoke('text')
.像<li>15</li>
这样的标签之间的值可以通过.invoke('text')
在单个元素上访问。
invoke('val')
is for <input>
and <textarea>
elements. invoke('val')
用于<input>
和<textarea>
元素。
But if you select multiple elements, the texts will mash together但是如果你 select 多个元素,文本会混在一起
cy.get('li') // multiple elements selected
.invoke('text') // joins all text together, result is "5153045"
.should('eq', '5153045') // passes
In your case it's ok, but feels a little clumsy.在你的情况下,没关系,但感觉有点笨拙。 In another scenario you can get additional white space between texts which makes it harder to compare.在另一种情况下,您可以在文本之间获得额外的空白,这使得比较更加困难。
You can use jQuery to extract individual texts, and they can be trimmed to make a better match when extra white-space is present您可以使用 jQuery 来提取单个文本,并且可以在存在额外空白时对其进行修剪以更好地匹配
cy.get('li')
.then($els => Cypress.$.map($els, (el) => el.innerText.trim())) // uses jQuery .map()
.should(values => {
expect(values).to.deep.eq(["5","15","30","45"])
})
But if your dropdown items are fetched from an API, you should put as much of the calculation as possible inside the .should()
callback, because Cypress retries until passing但是,如果您的下拉项目是从 API 中获取的,您应该将尽可能多的计算放在.should()
回调中,因为赛普拉斯会重试直到通过
cy.get('li')
.should($els => { // retries here
const values = [...$els].map(el => el.innerText.trim()) // uses Array .map()
expect(values).to.deep.eq(["5","15","30","45"])
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.