A short snippet that makes it possible to test if preserveScroll feature is enabled in InertiaJS. Can be used as a part of Test-Driven Development process (TDD). The snippet can probably be adapted for other scroll related tests, but is especially geared towards the InertiaJS feature called Scroll Regions like this:
<div class="overflow-y-auto" scroll-region>
<!-- Your page content -->
<!-- ... -->
<div data-cy="an-element-below" />
</div>
Now create a scroll preserving HTML link in InertiaJS or create an InertiaJS request with the same property in Javascript:
Inertia.get(route("post.show"), { post }, { preserveScroll: true })
Defining a div with a scroll-region
attribute on it makes it impossible
to use the common method of testing the window.scrollY
impossible as it
will always report 0. Instead, the scrollTop
on the element itself should
be observed like this:
cy.get("[data-cy=an-element-below]").scrollIntoView().should("be.visible")
cy.get("[scroll-region]").invoke("scrollTop").should("not.eq", 0)
The test like this makes sure that if you forgot or accidentally remove the
preserveScroll: true
from your templates, Cypress will let you know.
Links
- https://github.com/inertiajs/inertia/blob/dd5902978fa457fd4f065812c747c9c743fcafc8/packages/inertia-vue/tests/cypress/integration/manual-visits.test.js#L835
- https://github.com/inertiajs/inertia/blob/dd5902978fa457fd4f065812c747c9c743fcafc8/packages/inertia-vue/tests/app/Layouts/WithScrollRegion.vue#L29