React TanStack Virtualizer api getVirtualItems returns an empty array in RTA + Jest test

242 Views Asked by At

I am trying to test a table I created in React using TanStack Virtualizer with React testing library and jest. It works fine in the browser, but when I am testing the table I get back 0 items when I call rowVirtualizer.getVirtualItems, even though I am mocking the data and can see so in the test.

The code I am trying to test:

  const table = useReactTable<InvoiceRead>({
    data: flatData, // flatData is successfully being mocked in the test
    columns,
    state: {
      rowSelection,
    },
    getCoreRowModel: getCoreRowModel(),
    onRowSelectionChange: setRowSelection,
    debugTable: true,
    enableRowSelection: true,
  });

  // row array from the table
  const { rows } = table.getRowModel(); // these rows are successfully created in the test

  const rowVirtualizer = useVirtualizer({
    count: rows.length,
    estimateSize: () => 33,
    getScrollElement: () => tableContainerRef.current,
    // measure dynamic row height, except in firefox because it measures table border height incorrectly
    measureElement:
      typeof window !== "undefined" &&
      navigator.userAgent.indexOf("Firefox") === -1
        ? (element) => element?.getBoundingClientRect().height
        : undefined,
    overscan: 5,
  });

Then using the rows in my return:

          {rowVirtualizer.getVirtualItems().map((virtualRow) => {
            const row = rows[virtualRow.index] as Row<InvoiceRead>;
            return (
              <InvoiceTableRow
                row={row}
                isNewRow={newInvoiceIds.includes(row.original.invoiceId)}
                isSelectedRow={row.getIsSelected()}
                virtualRow={virtualRow}
                ref={(node) => rowVirtualizer.measureElement(node)}
                onCellClick={onCellClick}
                style={{
                  transform: `translateY(${virtualRow.start}px)`,
                  backgroundColor:
                    row.index % 2 === 0 ? "white" : "rgb(236, 237, 238, .5)",
                }}
              />
            );
          })}

The test simply renders the table and expects to see text on the screen from the first row of mock data. By debugging I have narrowed it down to the call I have to rowVirtualizer.getVirtualItems returning an empty array

1

There are 1 best solutions below

0
On

To fix this I had to add this snippet to my test file:

window.Element.prototype.getBoundingClientRect = jest .fn() .mockReturnValue({ height: 1000, width: 1000 });

Turns out react-virtual uses getBoundingClientRect to setup its rect, but jest does mock that for you.