We are running some tests for a website in Cypress. In Chrome on Windows, the tests all pass. On a Mac, however, the widths of some elements are 2px wider than when on Windows. I understand that this shouldn't be the case, and we'll investigate that separately, but what I would like to know is how do you tests that a value of a test should fall within a range of values?
This is the test that passes in Windows:
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.should('have.css', 'width', '569px')
})
This one passes on a Mac. The only change is the width being 571px
instead of 569px
.
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.should('have.css', 'width', '571px')
})
Given that the actual should()
test is against a string, how would you test that the width is either of two strings instead? Or an actual range of values?
We are running some tests for a website in Cypress. In Chrome on Windows, the tests all pass. On a Mac, however, the widths of some elements are 2px wider than when on Windows. I understand that this shouldn't be the case, and we'll investigate that separately, but what I would like to know is how do you tests that a value of a test should fall within a range of values?
This is the test that passes in Windows:
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.should('have.css', 'width', '569px')
})
This one passes on a Mac. The only change is the width being 571px
instead of 569px
.
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.should('have.css', 'width', '571px')
})
Given that the actual should()
test is against a string, how would you test that the width is either of two strings instead? Or an actual range of values?
2 Answers
Reset to default 3You could use closeTo
for that. It would look like this:
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.then($element => {
expect($element.width())
.closeTo(569, 2)
})
})
The first number of closeTo
is the wished number, the second number is the margin. For example: If you have .closeTo(600, 150)
the actual number should be between 450 and 750. So it isn't a very specific check.
I think I've found a better answer for my particular use case, though I really do like that there is a closeTo()
method available.
This is how I solved the problem:
it('checks Headline container, width & horizontal spacing', () => {
cy.get('[data-cy=headline]')
.should('have.css', 'width').and('match', /^(569|571)px/)
})
I used a regular expression to match both the string 569px
and 571px
.
This allows us to keep using should()
for the tests while ensuring that the value matches one of the two specific sizes we were expecting.