Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

code-splitter.test.ts

105 lines3.1 KB

1import { readFile, readdir } from 'node:fs/promises'
2import path from 'node:path'
3import { describe, expect, it } from 'vitest'
4​
5import {
6 compileCodeSplitReferenceRoute,
7 compileCodeSplitVirtualRoute,
8} from '../src/core/code-splitter/compilers'
9import { createIdentifier } from '../src/core/code-splitter/path-ids'
10import { defaultCodeSplitGroupings } from '../src/core/constants'
11import { frameworks } from './constants'
12import type { CodeSplitGroupings } from '../src/core/constants'
13​
14function getFrameworkDir(framework: string) {
15 const files = path.resolve(
16 __dirname,
17 `./code-splitter/test-files/${framework}`,
18 )
19 const snapshots = path.resolve(
20 __dirname,
21 `./code-splitter/snapshots/${framework}`,
22 )
23 return { files, snapshots }
25​
26const testGroups: Array<{ name: string; groupings: CodeSplitGroupings }> = [
27 {
28 name: '1-default',
29 groupings: defaultCodeSplitGroupings,
30 },
31 {
32 name: '2-components-combined-loader-separate',
33 groupings: [
34 ['loader'],
35 ['component', 'pendingComponent', 'errorComponent', 'notFoundComponent'],
36 ],
37 },
38 {
39 name: '3-all-combined-errorComponent-separate',
40 groupings: [
41 ['loader', 'component', 'pendingComponent', 'notFoundComponent'],
42 ['errorComponent'],
43 ],
44 },
46​
47describe('code-splitter works', () => {
48 describe.each(frameworks)('FRAMEWORK=%s', (framework) => {
49 describe.each(testGroups)(
50 'SPLIT_GROUP=$name',
51 async ({ groupings: grouping, name: groupName }) => {
52 const dirs = getFrameworkDir(framework)
53 const filenames = await readdir(dirs.files)
54​
55 it.each(filenames)(
56 `should compile "reference" for "%s"`,
57 async (filename) => {
58 const file = await readFile(path.join(dirs.files, filename))
59 const code = file.toString()
60​
61 const compileResult = compileCodeSplitReferenceRoute({
62 code,
63 filename,
64 id: filename,
65 addHmr: false,
66 codeSplitGroupings: grouping,
67 targetFramework: framework,
68 })
69​
70 await expect(compileResult?.code || code).toMatchFileSnapshot(
71 path.join(dirs.snapshots, groupName, filename),
72 )
73 },
74 )
75​
76 it.each(filenames)(
77 `should compile "virtual" for "%s"`,
78 async (filename) => {
79 const file = await readFile(path.join(dirs.files, filename))
80 const code = file.toString()
81​
82 for (const targets of grouping) {
83 const ident = createIdentifier(targets)
84​
85 const splitResult = compileCodeSplitVirtualRoute({
86 code,
87 filename: `${filename}?${ident}`,
88 splitTargets: targets,
89 })
90​
91 const snapshotFilename = path.join(
92 dirs.snapshots,
93 groupName,
94 `${filename.replace('.tsx', '')}@${ident}.tsx`,
95 )
96 await expect(splitResult.code).toMatchFileSnapshot(
97 snapshotFilename,
98 )
99 }
100 },
101 )
102 },
103 )
104 })
105})