Home > Net >  How to test element's width in cypress when the calculated width isn't accurate?
How to test element's width in cypress when the calculated width isn't accurate?

Time:05-28

Let's say I have a div in the DOM with '200px' of width and a class of 'target'.

In order to test its width with cypress, I should write the code below:

cy.get('.target').should('have.css', 'width', '200px');

and there's a bunch of tests, testing widths and heights of elements...

...

Today something weird happened!

All these tests have failed because the value of width that cypress found was 200.0000000000032038879956012px instead of 200px !!!

The first solution that came into my mind was to test them on the actual numbers (ex, 200), instead of the string (ex, '200px') that the cypress found; which I think is an expensive idea!

How do you think I can overcome this issue!?

CodePudding user response:

The test assertion .should('have.css', ...) is a wrapper for Window.getComputedStyle() which reads the actual rendered value after all CSS has been applied.

It won't always correspond to the "input" setting applied in an inline style or via a style sheet, depending on other settings like justification, flex settings, media queries.

From a test perspective, you can switch to testing the "input" paramters,

  • for inline styles
    .should('have.style', 'width', '200px')
  • for style sheets
    .should('have.class', 'target')

Alternatively use the chai-almost plugin to check close numeric values.

const chaiAlmost = require('chai-almost');
chai.use(chaiAlmost(1))                           // 1 pixel variance

cy.get('.target')
  .invoke('css', 'width')                         // extract computed width 
  .then(widthStr =>  widthStr.replace('px', ''))  // convert to number
  .should('almost.equal', 200);                   // approximate assertion

CodePudding user response:

You can convert the 200px first into a number and then check that the number is in the range. Something like:

cy.get('.target')
  .invoke('css', 'width')
  .then((width) => {
    expect( width.replace('px', '')).to.be.within(200, 201)
  })
  • Related