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

clientOnlyJSX.test.ts

104 lines2.8 KB

1import { readFile, readdir } from 'node:fs/promises'
2import path from 'node:path'
3import { describe, expect, test } from 'vitest'
4​
5import {
6 detectKindsInCode,
7 StartCompiler,
8} from '../../src/start-compiler/compiler'
9​
10// Default test options for StartCompiler
11function getDefaultTestOptions(env: 'client' | 'server') {
12 const envName = env === 'client' ? 'client' : 'ssr'
13 return {
14 envName,
15 root: '/test',
16 framework: 'react' as const,
17 providerEnvName: 'ssr',
18 }
20​
21async function compile(opts: {
22 env: 'client' | 'server'
23 code: string
24 id: string
25}) {
26 const compiler = new StartCompiler({
27 ...opts,
28 ...getDefaultTestOptions(opts.env),
29 loadModule: async () => {
30 // do nothing in test
31 },
32 lookupKinds: new Set(['ClientOnlyJSX']),
33 lookupConfigurations: [
34 // ClientOnly JSX component from TanStack router packages
35 {
36 libName: '@tanstack/react-router',
37 rootExport: 'ClientOnly',
38 kind: 'ClientOnlyJSX',
39 },
40 ],
41 getKnownServerFns: () => ({}),
42 resolveId: async (id) => {
43 return id
44 },
45 })
46 const result = await compiler.compile({
47 code: opts.code,
48 id: opts.id,
49 })
50 return result
52​
53async function getFilenames() {
54 return await readdir(path.resolve(import.meta.dirname, './test-files'))
56​
57describe('ClientOnlyJSX compiles correctly', async () => {
58 const filenames = await getFilenames()
59​
60 describe.each(filenames)('should handle "%s"', async (filename) => {
61 const file = await readFile(
62 path.resolve(import.meta.dirname, `./test-files/${filename}`),
63 )
64 const code = file.toString()
65​
66 // ClientOnlyJSX is only transformed on server
67 test(`should compile for ${filename} server`, async () => {
68 const compiledResult = await compile({
69 env: 'server',
70 code,
71 id: filename,
72 })
73​
74 if (compiledResult) {
75 await expect(compiledResult.code).toMatchFileSnapshot(
76 `./snapshots/server/${filename}`,
77 )
78 } else {
79 // No transformation - for files where ClientOnly is not from TanStack
80 await expect('no-transform').toMatchFileSnapshot(
81 `./snapshots/server/${filename}`,
82 )
83 }
84 })
85 })
86​
87 test('ClientOnlyJSX should not be detected on client', () => {
88 const code = `
89 import { ClientOnly } from '@tanstack/react-router'
90 <ClientOnly>test</ClientOnly>
91 `
92 const detectedKinds = detectKindsInCode(code, 'client')
93 expect(detectedKinds.has('ClientOnlyJSX')).toBe(false)
94 })
95​
96 test('ClientOnlyJSX should be detected on server', () => {
97 const code = `
98 import { ClientOnly } from '@tanstack/react-router'
99 <ClientOnly>test</ClientOnly>
100 `
101 const detectedKinds = detectKindsInCode(code, 'server')
102 expect(detectedKinds.has('ClientOnlyJSX')).toBe(true)
103 })
104})