import React from 'react' import { render, fireEvent } from '@testing-library/react' import { useTable } from '../../hooks/useTable' import { useExpanded } from '../useExpanded' const makeData = () => [ { firstName: 'tanner', lastName: 'linsley', age: 29, visits: 100, status: 'In Relationship', progress: 50, }, { firstName: 'derek', lastName: 'perkins', age: 40, visits: 40, status: 'Single', progress: 80, }, { firstName: 'joe', lastName: 'bergevin', age: 45, visits: 20, status: 'Complicated', progress: 10, }, { firstName: 'jaylen', lastName: 'linsley', age: 26, visits: 99, status: 'In Relationship', progress: 70, }, ] const data = makeData() data[0].subRows = makeData() data[0].subRows[0].subRows = makeData() data[0].subRows[0].subRows[0].subRows = makeData() function Table({ columns: userColumns, data, SubComponent }) { const { getTableProps, headerGroups, rows, prepareRow, flatColumns, state: [{ expanded }], } = useTable( { columns: userColumns, data, }, useExpanded ) return ( <>
        {JSON.stringify({ expanded }, null, 2)}
      
{headerGroups.map(headerGroup => ( {headerGroup.headers.map(column => ( ))} ))} {rows.map((row, i) => { prepareRow(row) const { key, ...rowProps } = row.getRowProps() return ( {row.cells.map(cell => { return ( ) })} {!row.subRows.length && row.isExpanded ? ( ) : null} ) })}
{column.render('Header')}
{cell.render('Cell')}
{SubComponent({ row })}
) } function App() { const columns = React.useMemo( () => [ { Header: () => null, id: 'expander', Cell: ({ row }) => ( row.toggleExpanded()} > {row.isExpanded ? '👇' : '👉'} ), }, { Header: 'Name', columns: [ { Header: 'First Name', accessor: 'firstName', }, { Header: 'Last Name', accessor: 'lastName', }, ], }, { Header: 'Info', columns: [ { Header: 'Age', accessor: 'age', }, { Header: 'Visits', accessor: 'visits', }, { Header: 'Status', accessor: 'status', }, { Header: 'Profile Progress', accessor: 'progress', }, ], }, ], [] ) return ( (
          {JSON.stringify({ values: row.values }, null, 2)}
        
)} /> ) } test('renders an expandable table', () => { const { getAllByText, asFragment } = render() let expandButtons = getAllByText('👉') const beforeGrouping = asFragment() fireEvent.click(expandButtons[0]) const afterGrouping1 = asFragment() expandButtons = getAllByText('👉') fireEvent.click(expandButtons[0]) const afterGrouping2 = asFragment() expandButtons = getAllByText('👉') fireEvent.click(expandButtons[0]) const afterGrouping3 = asFragment() expandButtons = getAllByText('👉') fireEvent.click(expandButtons[0]) const afterGrouping4 = asFragment() expect(beforeGrouping).toMatchDiffSnapshot(afterGrouping1) expect(afterGrouping1).toMatchDiffSnapshot(afterGrouping2) expect(afterGrouping2).toMatchDiffSnapshot(afterGrouping3) expect(afterGrouping3).toMatchDiffSnapshot(afterGrouping4) })