T
TanStack3y ago
passive-yellow

How do I mock the dimensions and scrolling for testing?

I need to test a behavior that only triggers after scrolling the list to the end. Is there a suggestion on which things I should mock to achieve this? I've been trying some things (HTMLElement.prototype.scrollHeight, HTMLElement.prototype.getBoundingClientRect) but virtual always renders all the elements.
4 Replies
passive-yellow
passive-yellowOP3y ago
I'm using React, jest and @testing-library/react
national-gold
national-gold3y ago
if I remember correctly it won't render all the items in test, it assumes 0 size of the container and render the amount in overscan and I think you can set the scrollOffset in the options of the virtualizer (won't be fun to do in tests but might work)
genetic-orange
genetic-orange3y ago
There are two options, when testing useVirtual, you can pass directly, observeElementRect, measureElement
observeElementRect: (_, cb) => {
cb({ height: 200, width: 0 })
},
measureElement: () => 100,
observeElementRect: (_, cb) => {
cb({ height: 200, width: 0 })
},
measureElement: () => 100,
fist will mock the container size, second element size ( in dynamic mode ) other, mock the getBoundingClientRect and return correct values for those elements. To fire scroll events you need to wrap scrollTo, something like
const scrollContainer = screen.getByRole('listbox')
const scrollTo = jest.fn(({ top }) => {
fireEvent.scroll(scrollContainer, {
target: { scrollTop: top },
})
})
scrollContainer.scrollTo = scrollTo
const scrollContainer = screen.getByRole('listbox')
const scrollTo = jest.fn(({ top }) => {
fireEvent.scroll(scrollContainer, {
target: { scrollTop: top },
})
})
scrollContainer.scrollTo = scrollTo
Overall as jsdom don't suport layout testing this is really hard. Internally with testing the lib i want change to Playwright components https://playwright.dev/docs/test-components
Experimental: components | Playwright
Playwright Test can now test your components.
passive-yellow
passive-yellowOP3y ago
I wasn't able to achieve it only with getBoundingClientRect, and did the observeElementRect/measureElement approach. Interestingly, I also had to manually import and pass those down to the function for it to work, as jest.mock didn't work when those were used as default inside the library. Not sure if it's a jest issue.

Did you find this page helpful?