Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if element width is less than or equal to a pixel size in Cypress?

Tags:

cypress

My goal is to write a test in Cypress that checks if the width of an element is less than or equal to 355px.

I have this code, but it only checks the exact dimension:

cy
.get('.mat-dialog-container:visible')
.should('have.css', 'width', '355px')
like image 245
DauleDK Avatar asked Dec 10 '19 11:12

DauleDK


1 Answers

Anything that can be automated, should be (unless the expected utility of doing so is outweighed by the cost of implementation and maintenance, of course), thus I think that automating RD tests is a good idea. Whether checking container dimensions is the way to achieve it is an open question (one could say that you should instead check wether elements that should be hidden, are hidden, and elements which should be visible, are visible, and whether the UI is working as expected).

Alas, here's how to achieve what you want.

I'd go with jQuery's outerWidth which is what you will usually want to check instead of width (in case there's padding or border):

cy.get(selector).invoke('outerWidth').should('be.lt', 355);

If you really wish to assert the actual computed css value, you can indeed use jQuery css helper (or use window.getComputedStyle, it doesn't really matter):

cy.get(selector).invoke('css', 'width')
    .then(str => parseInt(str)).should('be.lt', 355);

// or use jQuery.prototype.width (I'm not sure if there's any meaningful
//  difference, but there might be --- better check the docs)
cy.get(selector).invoke('width').should('be.lt', 355);
like image 91
dwelle Avatar answered Sep 21 '22 11:09

dwelle