React TanStack Virtualizer api getVirtualItems 在 RTA + Jest 测试中返回空数组

问题描述 投票:0回答:1

我正在尝试使用 TanStack Virtualizer 以及 React 测试库和笑话来测试我在 React 中创建的表。它在浏览器中工作正常,但是当我测试表时,当我调用

rowVirtualizer.getVirtualItems
时,我会返回 0 个项目,即使我正在模拟数据并且可以在测试中看到这一点。

我正在尝试测试的代码:

  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,
  });

然后使用我的退货中的行:

          {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)",
                }}
              />
            );
          })}

测试只是渲染表格,并期望在屏幕上看到模拟数据第一行的文本。通过调试,我已将其范围缩小到我必须

rowVirtualizer.getVirtualItems
返回空数组

的调用
reactjs jestjs tanstack tanstack-table react-virtual
1个回答
0
投票

要解决此问题,我必须将此代码段添加到我的测试文件中:

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

结果react-virtual使用getBoundingClientRect来设置它的矩形,但是jest确实为你模拟了它。

© www.soinside.com 2019 - 2024. All rights reserved.