Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[data grid] Testing with react testing library #1151

Open
2 tasks done
benjamin-schneider opened this issue Mar 3, 2021 · 46 comments
Open
2 tasks done

[data grid] Testing with react testing library #1151

benjamin-schneider opened this issue Mar 3, 2021 · 46 comments
Labels
component: data grid This is the name of the generic UI component, not the React module! docs Improvements or additions to the documentation priority: important This change can make a difference test

Comments

@benjamin-schneider
Copy link

benjamin-schneider commented Mar 3, 2021

With the component @material-ui/data-grid I am unable to get the rows rendered in a jest / react-testing-library environment. I use jest and material-ui since years, and this is the first time I do not manage to find any solution.

  • The issue is present in the latest release.
  • I have searched the issues of this repository and believe that this is not a duplicate.

Current Behavior 😯

I want to test a fully renderer datagrid. To test if a cell in a row il well formatted, to test row clicks, etc. Unfortunately, I don't manage to render the rows. In debug mode, I get :

<div
  class="rendering-zone"
  style="max-height: 36px; width: 900px; pointer-events: unset; transform: translate3d(-0px, -NaNpx, 0);"
/>

I saw this line in the internal tests : https://github.com/mui-org/material-ui-x/blob/master/packages/grid/x-grid/src/tests/rows.XGrid.test.tsx#L43
Maybe it it actually not possible to achieve testing rows :(

Expected Behavior 🤔

I would like datagrid to fully render in a jest/jestdom env.

Steps to Reproduce 🕹

Here is a very minimal repro to isolate :

import { DataGrid } from '@material-ui/data-grid';
import { render } from '@testing-library/react';
const Repro = () => {
  return (
    <DataGrid
      columns={
        [
          {
            field: 'field',
            headerName: 'col',
            flex: 1,
          },
        ]
      }
      rows={[
        {
          id: 'row1',
          field: 'row',
        },
      ]}
    />
  );
};

const createRender = () => {
  return render(<Repro />);
};

describe('Datagrid problem repro', () => {
  it('should render col', () => {
    const { getByText } = createRender();
    expect(getByText('col')).toBeInTheDocument();
  });
  it('should render row', () => {
    const { getByText } = createRender();
    expect(getByText('row')).toBeInTheDocument();
  });
});

First test (cols or headings) passes, testing rows fails

Your Environment 🌎

Ubuntu 20.04 / jest

Progress on the solution

#1151 (comment)

@oliviertassinari oliviertassinari transferred this issue from mui/material-ui Mar 3, 2021
@oliviertassinari oliviertassinari added the status: waiting for maintainer These issues haven't been looked at yet by a maintainer label Mar 3, 2021
@oliviertassinari oliviertassinari added component: data grid This is the name of the generic UI component, not the React module! test and removed status: waiting for maintainer These issues haven't been looked at yet by a maintainer labels Mar 8, 2021
@oliviertassinari
Copy link
Member

oliviertassinari commented Mar 8, 2021

@benjamin-schneider Did you find a solution?

I have looked at this problem a few months ago when I started to share the testing stack of the main repository with this one. I have stopped looking after failing to make the AutoSizer return my fake data in jsdom. So I ended up adding:

https://github.com/mui-org/material-ui-x/blob/59ef9dc874c49ae9be1f25b03339aef0026db884/packages/grid/data-grid/src/tests/components.DataGrid.test.tsx#L30-L33

I'm reopening because it's important. Developers should be able to tests their grid without having to rely on an actual browser as we do (it's not very common for UI components tests inside web applications). As far as I have pushed the exploration, I can think of two paths:

  1. We keep looking into what needs to be mocked in the tests in order for them to render without an empty cell. This might requires some not really pretty code (verbose and brittle).
  2. We add special logic in the source to behave nicely in the test environment. It's something we have already done in the past for the core components.

If you are using jest, you could probably mock the component as it's done in bvaughn/react-window#454 (comment).

A bit of caution. I'm not completely sure that it's something that possible. jsdom might be missing some APIs in order for the grid to work well. This is not a simple button component.

@oliviertassinari oliviertassinari changed the title testing @material-ui/data-grid with react testing library [DataGrid] Testing with react testing library Mar 8, 2021
@dtassone
Copy link
Member

dtassone commented Mar 8, 2021

try to wrap your <DataGrid /> around a div that has a prefixed height and width as the grid calculates what to render according to the size of its parent container

<div style={{ width: 300, height: 300 }}>
  <DataGrid .../>
</div>,

@oliviertassinari
Copy link
Member

oliviertassinari commented Mar 8, 2021

@dtassone jsdom has no layout capabilities, the width/height would have no effects.

@benjamin-schneider
Copy link
Author

@oliviertassinari Hi, thanks for your anwser. I did not find a solution, I just closed to avoid polluting your issues as I was thinking I was maybe wrong.
I did not manage to mock the AutoSize component (with jest) correctly, it never enters in the mock function :

jest.mock('@material-ui/data-grid', () => {
  const original = jest.requireActual('@material-ui/data-grid');
  return {
    ...original,
    AutoSizer: ({ children }: AutoSizerProps) => {
      console.log('mocked AutoSizer');
      return children({
        height: 500,
        width: 500,
      });
    },
  };
});

This was just a five minutes try...
I will try to investigate further as soon as I will find some time to understand the internals.
Thanks a lot for all your work on the best React UI library.

@oliviertassinari oliviertassinari added the waiting for 👍 Waiting for upvotes label Mar 9, 2021
@oliviertassinari
Copy link
Member

oliviertassinari commented Mar 9, 2021

@benjamin-schneider I have also spent 5 minutes looking at this yesterday. After solving the autosize issue, I was facing a .scrollTo missing API in jsdom 🙈. I have stopped there because I had to look at more pressing matters.

I have added the waiting for users upvotes tag. It will help evaluate if this is a frequent requirement. Fixing jsdom might be challenging and ever more as we add complexity in the internals of the component.

@dtassone
Copy link
Member

dtassone commented Mar 9, 2021

@oliviertassinari How about we add 2 props to force the height and width of AutoSizer
bvaughn/react-virtualized#493 (comment)

@oliviertassinari
Copy link
Member

oliviertassinari commented Mar 9, 2021

@dtassone Yeah, maybe we could do this for test only purposes. It could solve one part of the issue.

I think that we need to understand all the implications of supporting the rendering inside jsdom before making changes. There might be even bigger issues.

I also think that we can wait for more upvotes before dedicating time to it. It's unclear if developers want this. Intuitively, I would assume that many want it, but it seems costly, so if we can live without it, that's even better 🙃.

@DavidHanover
Copy link

DavidHanover commented Apr 1, 2021

just chiming in to say I'm having a bear of a time trying to test for row content in @material-ui/core/DataGrid. Tried everything in the past 48 hours & can't get the rows to even render within ReactTestingLibrary

UPDATE: finally got stuff to render. needed the "autoheight" param. for some reason it renders in the browser but not in the tests. needs autoheight. go figure

@oliviertassinari
Copy link
Member

oliviertassinari commented Apr 1, 2021

@DavidHanover The autoHeight approach sounds interesting. It might actually be good enough in many of the cases. It basically disables the row virtualization.

@gap777
Copy link

gap777 commented Apr 9, 2021

Since you're wondering, we're also feeling this pain. We've been using Xgrid for about 4 mos, and felt almost immediate pain since we're a TDD shop. Found a workaround with alpha18 by setting a fixed width on the Grid's parent tied to a theme variable being set in test env only, but that stopped working in alpha24. BTW, we're testing with jest + RTL.

@oliviertassinari
Copy link
Member

oliviertassinari commented Apr 10, 2021

@gap777 What aspects are you testing on the data grid? Are you testing simple interactions, like what rows are displayed or more advanced things?

#1361 is one step toward the resolution of this issue. With it, developers can test that the rows prop renders the correct
value.

@gap777
Copy link

gap777 commented Apr 10, 2021 via email

@oliviertassinari
Copy link
Member

oliviertassinari commented Apr 10, 2021

@gap777 Ok great. This is covered by #1361.

For closing the issue. I would propose the following requirements:

On the approach, I could find this interesting comment. ag-grid/ag-grid#4165 (comment). They have a prop to disable the virtualization. I guess we will know more about the challenges with our grid as me make progress on 2.

@oliviertassinari
Copy link
Member

Since #1361, we now run 69% of our tests inside jsdom (and 100% inside real browsers).

@benjamin-schneider
Copy link
Author

Very good job with the coverage improvements, thanks !
Finally, with forced autoHeight like suggested, we can render every Datagrids in our codebase without having to touching the source component, which was mandatory for us. If it can be helpful, here is small snippet :

import type { DataGridProps } from '@material-ui/data-grid';
jest.mock('@material-ui/data-grid', () => {
  const { DataGrid } = jest.requireActual('@material-ui/data-grid');
  return {
    ...jest.requireActual('@material-ui/data-grid'),
    DataGrid: (props: DataGridProps) => {
      return (
        <DataGrid
          {...props}
          autoHeight
        />
      );
    },
  };
});

@Eyegee-Eleven
Copy link

Eyegee-Eleven commented May 26, 2021

This is still causing me major issues :( Even if I look for row in my test It only slightly increase test coverage as opposed to the large increase when using a failing test that looks for the specific text I expect to be found in a cell after an API call is placed. Hopping to see a further resolution of this issue come down the pipe.

@oliviertassinari
Copy link
Member

@Eyegee-Eleven do you have an example of a case you can't test? (please provide a codesandbox).

@ModPhoenix
Copy link

For CRA based src/setupTests.tsx:

import { DataGridProps } from '@mui/x-data-grid';

jest.mock('@mui/x-data-grid', () => {
  const { DataGrid } = jest.requireActual('@mui/x-data-grid');
  return {
    ...jest.requireActual('@mui/x-data-grid'),
    DataGrid: (props: DataGridProps) => {
      return <DataGrid {...props} disableVirtualization />;
    },
  };
});

@caedes
Copy link

caedes commented May 17, 2022

I ran into the same problem today in a project. @ModPhoenix 's solution works perfectly!

@Rafael805
Copy link

I'm using the following:

render(<DataGrid rows={items} columns={columns} columnBuffer={columns.length} disableVirtualization />);

but my test is still not showing all of the columns.

On the grid it says it has a aria-colcount="5"

@tigerabrodi
Copy link

tigerabrodi commented Aug 9, 2022

@oliviertassinari @m4theushw @dtassone @samuelsycamore

I'm encountering a similar issue but in my case using the Data Grid Pro, I need to change the aria-label of the checkbox, so that it is unique, we need to include the name in the accessible name if the checkbox.

The issue we're having is passing the name as a prop to baseCheckbox how do we get the name of each row and pass it as a prop?

Or is there another recommended or better approach to this, we want to find the input by the role checkbox and then its name, we're using Cypress and Testing library.

Thanks!

              componentsProps={{
                baseCheckbox: { name: /* I want to pass the name here, how can I do it? */ }
              }}
              ```

@oliviertassinari
Copy link
Member

I need to change the aria-label of the checkbox, so that it is unique

@narutosstudent Why?

@flaviendelangle flaviendelangle changed the title [DataGrid] Testing with react testing library [data grid] Testing with react testing library Oct 17, 2022
@n-junge
Copy link

n-junge commented Dec 20, 2022

The problem still exists for me. Neither columnBuffer, disableVirtualization nor autoHeight solve my tests. Not a single column is "rendered" in the tests, despite this output:

<div
  aria-colcount="8"
  aria-multiselectable="false"
  aria-rowcount="3"
  class="MuiDataGrid-root MuiDataGrid-autoHeight MuiDataGrid-root--densityStandard css-15fuvc0-MuiDataGrid-root"
  role="grid"
>

@cbush06
Copy link

cbush06 commented Dec 20, 2022

The problem still exists for me. Neither columnBuffer, disableVirtualization nor autoHeight solve my tests. Not a single column is "rendered" in the tests, despite this output:

<div
  aria-colcount="8"
  aria-multiselectable="false"
  aria-rowcount="3"
  class="MuiDataGrid-root MuiDataGrid-autoHeight MuiDataGrid-root--densityStandard css-15fuvc0-MuiDataGrid-root"
  role="grid"
>

I'm having this issue. I have a button that, when clicked, adds a row to the DataGrid and places that row into edit mode. The row is added, but it never enters edit mode each cell is only a self-closing DIV.

@RafaelAugustScherer
Copy link

@Rafael805 , @n-junge have you tried adding @ModPhoenix's solution? You can add it before the describe sentence, not necessarly in src/setupTests.js. That worked for me!

@dnikhila

This comment was marked as off-topic.

@gdams
Copy link

gdams commented May 11, 2023

@dnikhila I've observed the same issue here: adoptium/adoptium.net#1758

@gdams

This comment was marked as resolved.

@gdams

This comment was marked as resolved.

@luizeboli

This comment was marked as resolved.

@Matt-Tranzact

This comment was marked as resolved.

@dep

This comment was marked as resolved.

@TrueWill
Copy link

I'm seeing valueFormatter columns rendering but valueGetter columns not. The getter doesn't even fire.

@agersea
Copy link

agersea commented Sep 18, 2023

I was also having trouble writing tests. Using renderCell seems to be the culprit as the tests pass when I remove all of the column definitions that use this function.

#1151 (comment) resolved the issue.

@vileppanen
Copy link

For CRA based src/setupTests.tsx:

import { DataGridProps } from '@mui/x-data-grid';

jest.mock('@mui/x-data-grid', () => {
  const { DataGrid } = jest.requireActual('@mui/x-data-grid');
  return {
    ...jest.requireActual('@mui/x-data-grid'),
    DataGrid: (props: DataGridProps) => {
      return <DataGrid {...props} disableVirtualization />;
    },
  };
});

Had issues with rendering all the columns in the grid. The disableVirtualization did the trick in my case, had a client bootstrapped with Vite.

@PrimaMateria
Copy link

For me, it worked only after I used mockResizeObserver as described here: https://stackoverflow.com/a/76571162/1209448

@lanceheld
Copy link

I'm using autoPageSize so when I'm testing for rows, I set a testingRows prop to true in order to get things to work:
<DataGrid autoPageSize={!testingRows} autoHeight={testingRows} />

@frankPairs
Copy link

frankPairs commented Apr 26, 2024

hey everyone! I am experiencing the same issue after updating the data-grid package from version 6.19.10 to 7.3.1.

More concretely, upgrading the version made a test faling. This test is executing some filtering and checking if the rows are filtered correctly. The problem is that the rowCount is showing a number, but not all of the rows are being rendered on the tests.

I tried the solution proposed by @ModPhoenix of adding the disableVirtualization property for testing but it did not worked.

I am using the next react testing library versions:

    "@testing-library/jest-dom": "6.4.2",
    "@testing-library/react": "14.3.1",
    "@testing-library/user-event": "14.5.2",

Any thoughts on how can be fixed?

Thanks a lot in advance!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
component: data grid This is the name of the generic UI component, not the React module! docs Improvements or additions to the documentation priority: important This change can make a difference test
Projects
None yet
Development

No branches or pull requests