Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Layout shift #245

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ The Cypress API enables you to configure the behavior of how Cypress works inter
- [root element attributes](./recipes/root-attributes.md)
- [Parse Email URL](./recipes/parse-email-url.md)
- [Find All Buttons Without `data-cy` attribute](./recipes/find-buttons-without-data-cy.md)
- Detect [layout shift](./recipes/layout-shift.md)

### Working with the window object

Expand Down
53 changes: 53 additions & 0 deletions docs/recipes/layout-shift.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Layout Shift

📺 Watch this recipe explained in the video [Test Layout Shift](https://youtu.be/5OTqNxJyhxo).

<!-- fiddle Detect layout shift -->

```html hide
<button id="like">Like</button>
<div id="status">🩶</div>
<div id="other">Some text after...</div>
```

Change the CSS below to give the liked element some small padding. This will make the test fail, since we will detect the vertical shift.

```css hide
.liked {
padding-top: 0px;
}
```

```js app hide
let liked = false
const heart = document.getElementById('status')
document.getElementById('like').addEventListener('click', () => {
if (!liked) {
liked = true
heart.innerText = '❤️'
heart.classList.add('liked')
} else {
liked = false
heart.innerText = '🩶'
heart.classList.remove('liked')
}
})
```

Let's use [offsetTop](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop) property to remember the element's position at the start of the interaction.

```js hide
cy.get('#other')
.should('have.prop', 'offsetTop')
.should('be.a', 'number')
.then((offsetTop) => {
// interact with the app
cy.contains('button', 'Like').click()
// check if the element remains at the same position vertically
cy.get('#other').should('have.prop', 'offsetTop', offsetTop)
})
```

We can detect the horizontal shift similarly using the `offsetLeft` property.

<!-- fiddle-end -->
22 changes: 5 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.