2

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

Seeker
  • 356
  • 1
  • 11
strongff
  • 23
  • 4

4 Answers4

2

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')
kegne
  • 583
  • 1
  • 8
1

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()

Fody
  • 23,754
  • 3
  • 20
  • 37
1

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)   
  })
Seeker
  • 356
  • 1
  • 11
0

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/)
Alapan Das
  • 17,144
  • 3
  • 29
  • 52