import { eachTree, filter, findNode, findPath, forEach, handleTree, handleTree2, treeMap, treeToList } from '@/utils/tree' interface Dept { id: number parentId: number name: string children?: Dept[] } const flat = (): Dept[] => [ { id: 1, parentId: 0, name: '财开' }, { id: 2, parentId: 1, name: '信息部' }, { id: 3, parentId: 1, name: '财务部' }, { id: 4, parentId: 2, name: '开发组' }, { id: 5, parentId: 99, name: '孤立节点' } ] describe('utils/tree', () => { it('handleTree 按 parentId 组装树,父节点不存在的作为根', () => { const tree = handleTree(flat()) expect(tree.map((n) => n.id)).toEqual([1, 5]) expect(tree[0].children!.map((n) => n.id)).toEqual([2, 3]) expect(tree[0].children![0].children![0].name).toBe('开发组') }) it('handleTree 非数组输入返回空数组', () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) expect(handleTree(null as unknown as Dept[])).toEqual([]) expect(warn).toHaveBeenCalled() }) it('handleTree 支持自定义字段名', () => { const data = [ { key: 'a', pid: '', label: 'A' }, { key: 'b', pid: 'a', label: 'B' } ] const tree = handleTree>(data, 'key', 'pid', 'items') expect(tree).toHaveLength(1) expect((tree[0].items as unknown[]).length).toBe(1) }) it('handleTree2 以 rootId 取根且不修改入参', () => { const files = [ { id: 'src', parentId: '/', label: 'src' }, { id: 'src/a.ts', parentId: 'src', label: 'a.ts' } ] const tree = handleTree2(files, 'id', 'parentId', 'children', '/') expect(tree).toHaveLength(1) expect((tree[0] as { children?: unknown[] }).children).toHaveLength(1) expect('children' in files[0]).toBe(false) // 默认根取最小 parentId const numeric = handleTree2(flat().slice(0, 4)) expect(numeric.map((n) => n.id)).toEqual([1]) }) it('treeToList / findNode / findPath / forEach 遍历', () => { const tree = handleTree(flat()) expect(treeToList(tree).map((n) => n.id)).toEqual([1, 2, 4, 3, 5]) expect(findNode(tree, (n) => n.id === 4)?.name).toBe('开发组') expect(findNode(tree, (n) => n.id === 404)).toBeNull() expect(findPath(tree, (n) => n.id === 4)?.map((n) => n.id)).toEqual([1, 2, 4]) expect(findPath(tree, (n) => n.id === 404)).toBeNull() const visited: number[] = [] forEach(tree, (n) => { visited.push(n.id) return n.id === 2 // 返回 true 终止遍历 }) expect(visited).toEqual([1, 2]) }) it('filter 保留命中节点及其祖先', () => { const tree = handleTree(flat()) const result = filter(tree, (n) => n.name === '开发组') expect(result.map((n) => n.id)).toEqual([1]) expect(result[0].children!.map((n) => n.id)).toEqual([2]) expect(result[0].children![0].children!.map((n) => n.id)).toEqual([4]) }) it('treeMap 转换结构,eachTree 传入父节点', () => { const tree = handleTree(flat()) const mapped = treeMap(tree, { conversion: (n: Dept) => ({ value: n.id, label: n.name }) }) expect(mapped[0]).toMatchObject({ value: 1, label: '财开' }) expect((mapped[0] as unknown as { children: unknown[] }).children).toHaveLength(2) const parents: Record = {} eachTree(tree, (node: Dept, parent: Dept) => { parents[node.id] = parent.name }) expect(parents[4]).toBe('信息部') expect(parents[1]).toBeUndefined() }) })