Reputation: 393
Below is my html for a dropdown control:
I want to verify that drop down has following items: ["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. Also, My html does not has the value attribute. How do i assert based on text ??
Upvotes: 3
Views: 9206
Reputation:
The values between tags like <li>15</li>
are accessed on individual element with .invoke('text')
.
invoke('val')
is for <input>
and <textarea>
elements.
But if you select multiple elements, the texts will mash together
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
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
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"])
})
Upvotes: 4
Reputation: 18626
Create a fixture file data.json
inside cypress/fixtures
and write:
{
"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])
})
})
})
Upvotes: 2