Skip to content

Instantly share code, notes, and snippets.

@zourdyzou
Created June 21, 2024 08:14
Show Gist options
  • Select an option

  • Save zourdyzou/e3f0701ba93ecff936c07b30430fc21b to your computer and use it in GitHub Desktop.

Select an option

Save zourdyzou/e3f0701ba93ecff936c07b30430fc21b to your computer and use it in GitHub Desktop.
import { renderHook } from '@testing-library/react-hooks';
import { describe, expect, it } from 'vitest';
import { useTreeFormatData } from './useFormatTreeData';
interface DataSample {
id: string;
name: string;
rootGroup: boolean;
parentGroupId?: string | null;
subGroups: DataSample[];
}
const inputData: DataSample[] = [
{
id: '1',
name: 'Group 1',
parentGroupId: null,
rootGroup: true,
subGroups: [],
},
{
id: '2',
name: 'Group 2',
parentGroupId: '1',
rootGroup: false,
subGroups: [],
},
{
id: '3',
name: 'Group 3',
parentGroupId: '1',
rootGroup: false,
subGroups: [],
},
{
id: '4',
name: 'Group 4',
parentGroupId: '2',
rootGroup: false,
subGroups: [],
},
];
const options = { childrenKey: 'subGroups', parentIdKey: 'parentGroupId' };
describe('useTreeFormatData', () => {
it('should format flat data into a tree structure', () => {
const { result } = renderHook(() =>
useTreeFormatData<DataSample>(inputData, options),
);
const tree = result.current;
expect(tree).toEqual([
{
id: '1',
name: 'Group 1',
rootGroup: true,
parentGroupId: null,
subGroups: [
{
id: '2',
name: 'Group 2',
parentGroupId: '1',
rootGroup: false,
subGroups: [
{
id: '4',
name: 'Group 4',
parentGroupId: '2',
rootGroup: false,
subGroups: [],
},
],
},
{
id: '3',
name: 'Group 3',
parentGroupId: '1',
rootGroup: false,
subGroups: [],
},
],
},
]);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment