#reactjs #jestjs #material-ui #react-testing-library
#reactjs #jestjs #материал-ui #react-testing-library
Вопрос:
Я хочу протестировать содержимое моего material-ui datagrid, но в тесте отображаются только первые 3 столбца (из 8). Я могу протестировать содержимое этих 3 столбцов, с этим проблем нет.
Все правильно отображается в веб-браузере.
Я думаю, что это связано с шириной и высотой отображаемой сетки данных, как указано в этих предупреждениях, но я не смог найти решение в документах.
Material-UI: useResizeContainer - The parent of the grid has an empty width.
You need to make sure the container has an intrinsic width.
The grid displays with a width of 0px.
You can find a solution in the docs:
https://material-ui.com/components/data-grid/rendering/#layout
Material-UI: useResizeContainer - The parent of the grid has an empty height.
You need to make sure the container has an intrinsic height.
The grid displays with a height of 0px.
You can find a solution in the docs:
https://material-ui.com/components/data-grid/rendering/#layout
Это также может быть связано с функцией монтирования: (Согласно документам material-ui, вы должны использовать функцию монтирования enzyme в качестве аргумента для функции createMount, но я использую react 17, а официальный адаптер enzyme еще не выпущен. Я пробовал с помощью @wojtekmaj / enzyme-adapter-react-17, но это ничего не изменило. В настоящее время я использую «рендеринг» из @testing-library / react)
const mount = createMount({mount:render})
Вот более простая версия моего компонента :
import React from "react";
import { DataGrid } from '@material-ui/data-grid';
import Button from "@material-ui/core/Button";
const Gridtest = (props) => {
const columns = [
{field: 'id', headerName: 'ID', type: 'number',headerAlign: 'left', width: 130 },
{field: 'tenant_id', headerName: 'Tenant ID', type: 'number',headerAlign: 'left', width: 130 },
{field: 'user_reference', headerName: 'Customer user reference', type: 'string',headerAlign: 'left', width: 250 },
{field: 'provider_name', headerName: 'Provider name', type: 'string',headerAlign: 'left', width: 220 },
{field: 'provider_id', headerName: 'Provider ID', type: 'number',headerAlign: 'left', width: 130 },
{field: 'expiration_date', headerName: 'Expiration date', type: 'dateTime',headerAlign: 'left', width: 220 },
{field: 'last_start', headerName: 'Last start date', type: 'dateTime',headerAlign: 'left', width: 130 },
{field: 'Action',
headerName: 'Action',
headerAlign: 'left',
width: 100,
renderCell: (params) => {
return (
<div>
<Button variant="contained" size="small" color="primary" disableRipple
onClick={() => null}>
Details
</Button>
</div>
)
},
},
];
const rows = [
{
"id": "10190",
"tenant_id": "12201",
"user_reference": "Xuser_ref",
"provider_name": "Xprovider",
"provider_id": "122",
"expiration_date": "2020-04-07T17:36:40 02:00",
"last_start": "2020-07-06T17:36:40 02:00"
},
{
"id": "23541",
"tenant_id": "96542",
"user_reference": "Yuser_ref",
"provider_name": "Yprovider",
"provider_id": "856",
"expiration_date": "2010-07-07T17:36:40 02:00",
"last_start": "2010-09-06T17:36:40 02:00"
}]
return(
<main>
<div style={{ display: 'flex', height: '100%',width: '100%', flexGrow: 1 }}>
<DataGrid style={{height: '100%', width: '100%'}} autoHeight rows={rows} columns={columns} pageSize={5} checkboxSelection={false} hideFooterSelectedRowCount/>
</div>
</main>
)};
export default Gridtest;
Тестовый файл для моего более простого компонента (тест завершен успешно) :
import {screen, render, act, findByTestId} from '@testing-library/react'
import React from 'react'
import '@testing-library/jest-dom/extend-expect'
import Gridtest from '../../src/Gridtest'
import { createMount } from '@material-ui/core/test-utils';
describe('grid test', () => {
const mount = createMount({mount:render})
test('grid render', async () => {
await act(async () => {
mount(
<Gridtest />
);
});
expect(await screen.findByRole('grid')).toBeInTheDocument()
expect(await screen.findAllByRole('columnheader')).toHaveLength(3)
screen.debug(await screen.findByRole('grid'))
})
})
screen.debug(ожидает screen.findByRole(‘grid’)) возвращает :
<div
aria-colcount="8"
aria-label="grid"
aria-multiselectable="false"
aria-rowcount="2"
class="MuiDataGrid-root MuiDataGrid-root"
role="grid"
style="width: 0px; height: 175px;"
tabindex="0"
>
<div />
<div
class="MuiDataGrid-mainGridContainer"
>
<div
class="MuiDataGrid-columnsContainer"
style="min-height: 56px; max-height: 56px; line-height: 56px;"
>
<div
aria-rowindex="1"
class="MuiDataGrid-colCellWrapper scroll"
role="row"
style="transform: translate3d(-0px, 0, 0); min-width: 1310px;"
>
<div
aria-colindex="1"
class="MuiDataGrid-colCell MuiDataGrid-colCellSortable MuiDataGrid-colCellNumeric"
data-field="id"
role="columnheader"
style="width: 130px; min-width: 130px; max-width: 130px;"
tabindex="-1"
>
<div
class="MuiDataGrid-colCell-draggable"
draggable="false"
>
<div
class="MuiDataGrid-colCellTitleContainer"
>
<div
aria-label="ID"
class="MuiDataGrid-colCellTitle"
title=""
>
ID
</div>
</div>
</div>
<div
class="MuiDataGrid-columnSeparator"
style="min-height: 56px; opacity: 1;"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root MuiDataGrid-iconSeparator"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M11 19V5h2v14z"
/>
</svg>
</div>
</div>
<div
aria-colindex="2"
class="MuiDataGrid-colCell MuiDataGrid-colCellSortable MuiDataGrid-colCellNumeric"
data-field="tenant_id"
role="columnheader"
style="width: 130px; min-width: 130px; max-width: 130px;"
tabindex="-1"
>
<div
class="MuiDataGrid-colCell-draggable"
draggable="false"
>
<div
class="MuiDataGrid-colCellTitleContainer"
>
<div
aria-label="Tenant ID"
class="MuiDataGrid-colCellTitle"
title=""
>
Tenant ID
</div>
</div>
</div>
<div
class="MuiDataGrid-columnSeparator"
style="min-height: 56px; opacity: 1;"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root MuiDataGrid-iconSeparator"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M11 19V5h2v14z"
/>
</svg>
</div>
</div>
<div
aria-colindex="3"
class="MuiDataGrid-colCell MuiDataGrid-colCellSortable"
data-field="user_reference"
role="columnheader"
style="width: 250px; min-width: 250px; max-width: 250px;"
tabindex="-1"
>
<div
class="MuiDataGrid-colCell-draggable"
draggable="false"
>
<div
class="MuiDataGrid-colCellTitleContainer"
>
<div
aria-label="Customer user reference"
class="MuiDataGrid-colCellTitle"
title=""
>
Customer user reference
</div>
</div>
</div>
<div
class="MuiDataGrid-columnSeparator"
style="min-height: 56px; opacity: 1;"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root MuiDataGrid-iconSeparator"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M11 19V5h2v14z"
/>
</svg>
</div>
</div>
<div
class="MuiDataGrid-cell MuiDataGrid-cellLeft"
role="cell"
style="min-width: 800px; max-width: 800px; line-height: 55px; min-height: 56px; max-height: 56px;"
/>
</div>
</div>
<div
class="MuiDataGrid-window"
style="top: 56px; overflow-y: hidden;"
>
<div
class="MuiDataGrid-dataContainer data-container"
style="min-height: 119px; min-width: 1310px;"
>
<div
class="MuiDataGrid-viewport"
style="min-width: 0; max-width: 0; min-height: 104px; max-height: 104px;"
>
<div
class="rendering-zone"
style="max-height: 275px; width: 1310px; pointer-events: unset; transform: translate3d(-0px, -0px, 0);"
>
<div
aria-rowindex="2"
aria-selected="false"
class="MuiDataGrid-row Mui-even"
data-id="10190"
data-rowindex="0"
role="row"
style="max-height: 52px; min-height: 52px;"
>
<div
aria-colindex="0"
class="MuiDataGrid-cell MuiDataGrid-cellRight"
data-field="id"
data-rowindex="0"
data-value="10190"
role="cell"
style="min-width: 130px; max-width: 130px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="0"
>
10190
</div>
<div
aria-colindex="1"
class="MuiDataGrid-cell MuiDataGrid-cellRight"
data-field="tenant_id"
data-rowindex="0"
data-value="12201"
role="cell"
style="min-width: 130px; max-width: 130px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="-1"
>
12201
</div>
<div
aria-colindex="2"
class="MuiDataGrid-cell MuiDataGrid-cellLeft"
data-field="user_reference"
data-rowindex="0"
data-value="Xuser_ref"
role="cell"
style="min-width: 250px; max-width: 250px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="-1"
>
Xuser_ref
</div>
<div
class="MuiDataGrid-cell MuiDataGrid-cellLeft"
role="cell"
style="min-width: 800px; max-width: 800px; line-height: 51px; min-height: 52px; max-height: 52px;"
/>
</div>
<div
aria-rowindex="3"
aria-selected="false"
class="MuiDataGrid-row Mui-odd"
data-id="23541"
data-rowindex="1"
role="row"
style="max-height: 52px; min-height: 52px;"
>
<div
aria-colindex="0"
class="MuiDataGrid-cell MuiDataGrid-cellRight"
data-field="id"
data-rowindex="1"
data-value="23541"
role="cell"
style="min-width: 130px; max-width: 130px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="-1"
>
23541
</div>
<div
aria-colindex="1"
class="MuiDataGrid-cell MuiDataGrid-cellRight"
data-field="tenant_id"
data-rowindex="1"
data-value="96542"
role="cell"
style="min-width: 130px; max-width: 130px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="-1"
>
96542
</div>
<div
aria-colindex="2"
class="MuiDataGrid-cell MuiDataGrid-cellLeft"
data-field="user_reference"
data-rowindex="1"
data-value="Yuser_ref"
role="cell"
style="min-width: 250px; max-width: 250px; line-height: 51px; min-height: 52px; max-height: 52px;"
tabindex="-1"
>
Yuser_ref
</div>
<div
class="MuiDataGrid-cell MuiDataGrid-cellLeft"
role="cell"
style="min-width: 800px; max-width: 800px; line-height: 51px; min-height: 52px; max-height: 52px;"
/>
</div>
</div>
</div>
</div>
</div>
</div>
<div>
<div
class="MuiDataGrid-footer"
>
<div />
<div
class="MuiTablePagination-root"
>
<div
class="MuiToolbar-root MuiToolbar-regular MuiTablePagination-toolbar MuiToolbar-gutters"
>
<div
class="MuiTablePagination-spacer"
/>
<p
class="MuiTypography-root MuiTablePagination-caption makeStyles-caption-1 MuiTypography-body2 MuiTypography-colorInherit"
>
1-2 of 2
</p>
<div
class="MuiTablePagination-actions"
>
<button
aria-label="Previous page"
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit Mui-disabled Mui-disabled"
disabled=""
tabindex="-1"
title="Previous page"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"
/>
</svg>
</span>
</button>
<button
aria-label="Next page"
class="MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit Mui-disabled Mui-disabled"
disabled=""
tabindex="-1"
title="Next page"
type="button"
>
<span
class="MuiIconButton-label"
>
<svg
aria-hidden="true"
class="MuiSvgIcon-root"
focusable="false"
viewBox="0 0 24 24"
>
<path
d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"
/>
</svg>
</span>
</button>
</div>
</div>
</div>
</div>
</div>
Спасибо за вашу помощь
Комментарии:
1. В опубликованном вами примере кода есть некоторые проблемы. Во-первых, компонент не показывает, откуда
columns
он берется, что, пожалуй, является самой важной деталью вашего вопроса. Кроме того, ваш тест содержит много кода, который не имеет отношения к вашему вопросу, например, издевательство над API, работа с маршрутизацией и выполнение мутаций. Я предлагаю вам написать гораздо более простой компонент / тест для демонстрации проблемы, а также включить DOM (изscreen.debug
).2. Меня также раздражают предупреждающие сообщения о том, что контейнер DataGrid имеет ширину 0, и я также использую библиотеку тестирования React. Не должно иметь значения, какое решение для тестирования используется. Метод «сетка имеет ширину 0» пахнет хакерством.
Ответ №1:
Я нашел решение: вы можете установить реквизит columnBuffer для datagrid.
Например columnBuffer={8}
, для 8 столбцов.
Комментарии:
1. Да, но я все еще получаю предупреждение MUI: «Material-UI: useResizeContainer — родительский элемент сетки имеет пустую ширину» в журналах, которые запутывают результаты моего тестового запуска.
2. @gap Похоже, что это была проблема с пакетом, если вы обновите его до более новой версии, она будет исправлена. Ошибка заключена в некоторую логику, чтобы проверить, является ли тестовая среда JSDOM
3. В более поздней версии вы можете полностью отключить виртуализацию с
disableVirtualization
помощью prop. Это заставляет сетку отображать все ячейки. mui.com/components/data-grid/virtualization /…
Ответ №2:
Это не имеет ничего общего с DataGrid, убедитесь, что ваш внешний контейнер по умолчанию занимает 100% высоты и ширины. Я столкнулся с той же проблемой, что и показано ниже:
Прочитав предупреждения, я понял, что размер контейнера необходимо изменить, поэтому я изменил CSS моего внешнего контейнера most на flexbox со всей шириной, как показано ниже:
{
display: flex;
flex-direction: column;
height: 100%;
width: 100%;
}
Если вы увидите мои два изображения, вы заметите разницу, из-за которой таблица не отображалась должным образом.
Комментарии:
1. это правильный ответ