1

I'm using react-testing-library with jest to test storybook stories. I have a component that, based on it's scrollWidth and the clientWidth it conditionally renders a button to page through the component:

function Collection({
  children,
  scrollOffset = DEFAULT_SCROLL_X_OFFSET,
  onScroll,
  ...rest
}: HorizontalChipCollectionProps) {
  const [scrollX, setScrollX] = useState(0); // For detecting start scroll postion
  const [showRightPager, setShowRightPager] = useState(false); // For detecting end of scrolling
  const scrollableAreaRef = useRef();

  const scrollableAreaCallback = React.useCallback((node) => {
    scrollableAreaRef.current = node;
    /** Check to see if the scrollWidth is less than the full width, if so hide the right arrow */
    if (node?.scrollWidth <= node?.clientWidth) {
      setShowRightPager(true);
    }
  }, [setShowRightPager]);

  const leftPageOnClick = () => pagerOnClick(PAGER_DIRECTION.LEFT);
  const rightPageOnClick = () => pagerOnClick(PAGER_DIRECTION.RIGHT);

  return (
    <Box>
      <ScrollableArea
        py={{
          base: 'xsmall',
          medium: 'small',
        }}
        display="flex"
        ref={scrollableAreaCallback}
        onScroll={scrollCurrCheck}
        overflowX="auto"
        css={css`
          > *:not(:last-child) {
            margin-right: var(--space-small);
          }
        `}
        {...rest}
      >
        {children}
      </ScrollableArea>
      {!showRightPager ? <Pager data-testid="right-pager" variant="right" onClick={rightPageOnClick} /> : null}
    </Box>
  );
}

I'm trying to test the rightPageOnClick to confirm it works but I'm unable to find the element in my test. Here is my test:

    test('should show pager buttons', () => {
      window.innerWidth = 1440;
      window.innerHeight = 900;
      window.dispatchEvent(new Event('resize'));
      render(<Basic />);
      const rightPager = screen.getByTestId('right-pager');
      expect(rightPager).toBeInTheDocument();
    });

Let me know if you need any more info from me!

  • Does this answer your question? [React Testing Library (RTL): test a responsive design](https://stackoverflow.com/questions/64281467/react-testing-library-rtl-test-a-responsive-design) – Cathal Mac Donnacha Nov 23 '21 at 23:20
  • @ReturnOfTheMac, unfortunately, no because it's more about setting the `showRightPager` value based on the screen size – Matthew Benjamin Nov 23 '21 at 23:57

0 Answers0