如何使用testing-library测试Ag-grid中的内容?

问题描述

我正在尝试编写一些简单的测试,以使我要渲染的标题和数据按预期显示。我创建了一个仓库-https://github.com/olore/ag-grid-testing-library进行复制。该表的外观与在浏览器中打开时的预期一样。

<AgGridReact
  columnDefs={ /* First 2 always findable,others never */
  [
    { field: "make" },{ field: "model" },{ field: "price" },{ field: "color" },]}
  rowData={
  [{ 
    make: "Toyota",model: "Celica",price: "35000",color: "blue" 
    }]
  }
  pagination={true}></AgGridReact>

和测试

test('renders all the headers',async () => {
  const { getByText } = render(<GridExample />);
  expect(getByText("Make")).toBeInTheDocument();  // PASS
  expect(getByText("Model")).toBeInTheDocument(); // PASS
  expect(getByText("Price")).toBeInTheDocument(); // FAIL
  expect(getByText("Color")).toBeInTheDocument(); // FAIL
});

在本地,前2列的标题和数据是可访问的,但其他列均未呈现,正如我在testing-library的输出中看到的那样。我正在按照其他帖子的建议使用--env=jsdom-fourteen

奇怪的是,当在此存储库的codeandBox中时,没有呈现用于测试的标头或数据,就本地而言,浏览器看起来是正确的。 https://codesandbox.io/s/gallant-framework-e54c7。然后,我尝试等待gridReady https://codesandbox.io/s/intelligent-minsky-wl17y,但没什么用。

编辑:还尝试过直接在onGridReady中调用一个函数,同样的问题(前两列通过,后两列失败)

test('renders all the headers',async (done) => {
  let page;

  const onReady = () => {
    expect(page.getByText("Make")).toBeInTheDocument();  // PASS
    expect(page.getByText("Model")).toBeInTheDocument(); // PASS
    expect(page.getByText("Price")).toBeInTheDocument(); // FAIL
    expect(page.getByText("Color")).toBeInTheDocument(); // FAIL
    done();
  }
  page = render(<GridExample ready={onReady}/>);
});

解决方法

ag-grid使用Column Virtualisation,因此这里的解决方案似乎是通过suppressColumnVirtualisation元素上的<AgGridReact>属性来禁用它。

  <AgGridReact
        suppressColumnVirtualisation={true}
        ...

轰!所有测试都通过!

实际上,仅在测试期间抑制这种情况可能是理想的:

        suppressColumnVirtualisation={process.env.NODE_ENV === "test"}