'Cypress / JavaScript: assertion with an URL value that contains a specific word
I'm a beginner with Cypress and JavaScript. I'm trying to improve the following assertion, I report it below.
Here:
cy.xpath('//div[@data-testid="column"]').should('have.css', 'background-image', 'url("https://assets.website.com/folder/house.jpg")');
In the test I am verifying if that div has the css background-image property with that url value, I am trying to convert this assertion in this way: verifying that the div has the css background-image property with a value that contains: “house.jpg” instead of the entire URL.
Many thanks if you can help me
Solution 1:[1]
You can also do it with a simple string include check
cy.xpath('//div[@data-testid="column"]')
.should('have.css', 'background-image') // changes subject to css value
.and('include', 'house.jpg')
Solution 2:[2]
What you need to shorten the url assertion is a partial string check, since house.js is part of url("https://assets.website.com/folder/house.jpg").
Cypress commands pass along a "subject" from one step to the next. So cy.xpath('//div[@data-testid="column"]') passes the whole element to .should().
You can change the subject from the element to it's background-image style value using the jQuery css() method.
cy.xpath('//div[@data-testid="column"]') // yields the element
.invoke('css', 'background-image') // applies .css('background-image') to
// the element and yields the string value
.should('include', 'house.jpg') // assert the value has "house.jpg"
Ref .invoke()
Solution 3:[3]
You can also use a callback function with .should() for more complicated checking.
cy.xpath('//div[@data-testid="column"]')
.should($el => {
const backgroundImage = $el.css('background-image')
expect(backgroundImage).to.include('house.jpg) // retries if expect() fails initially
})
Depending on how it is applied (style sheets or SCSS), you may have to use getComputedStyle to get the actual CSS value,
cy.xpath('//div[@data-testid="column"]')
.should($el => {
const backgroundImage = window.getComputedStyle($el[0])['background-image']
expect(backgroundImage).to.include('house.jpg)
})
Solution 4:[4]
You can also use a simple regex for assertion as well like this as mentioned in the cypress docs.
cy.xpath('//div[@data-testid="column"]')
.should('have.css', 'background-image')
.and('match', /house.jpg/)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Fody |
| Solution 3 | Seke |
| Solution 4 | Alapan Das |
