How to fireEvent.scroll on a element inside container with react-testing-library?
Asked Answered
T

2

32

I'm trying to simulate the scrolling in a element contained in a div, which is the one passed to render function.

I'm trying with something like this, but it seems that the div is not scrolling as my next expect is falling.

const content = (
      <div style={{display: 'flex'}}>
        <LazyList itemRenderer={itemRenderer} items={items} minItemHeight={MIN_ITEM_HEIGHT} />
      </div>
    );
mockOffsetSize(WIDTH, HEIGHT);

const {debug, container, queryByText} = render(content);
const scrollContainer = container.querySelector('.ReactVirtualized__Grid');
debug(scrollContainer);
fireEvent.scroll(scrollContainer, {y: 100});
debug(scrollContainer);

Is this the correct way of firing the scroll event? Any other alternatives?

Taneka answered 5/10, 2018 at 12:8 Comment(2)
Any luck scrolling the element?Defection
I have left this part unfinished until I have time or someone proposes a solution...Taneka
P
21

Have you tried adding EventListener to your scroll container? I'm just not sure with that library you may have just used, but I'm pretty sure, in normal situations, calling scroll fireEvent without listener won't execute anything. Before your fireEvent, insert something like this:

scrollContainer.addEventListener('scroll', () => { /* some callback */ });

and change your fireEvent to:

fireEvent.scroll(scrollContainer, { target: { scrollY: 100 } });
Piderit answered 21/5, 2019 at 8:0 Comment(3)
@Taneka is the listener added to the container itself or is it a window listener? If so, you can fireEvent.scroll(window, { target: { scrollY: 100 } }) or fireEvent.scroll(global, { target: { scrollY: 100 } })Gone
scrollY and scrollX only exists on the window object, I used scrollTop and scrollLeft to make it work with an html element.Qua
Thanks @colinD! I didn't know that for html elements I had to use scrollLeft.Chirrup
R
0

scrollY describes the scroll position of the entire document. Use scrollLeft for individual containers.

const scrollContainer = /* query */;
fireEvent.scroll(scrollContainer, { target: { scrollLeft: 500 } });
Rim answered 11/8, 2023 at 19:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.