diff --git a/packages/router-generator/tests/generator-fixture.ts b/packages/router-generator/tests/generator-fixture.ts
index ee859c892b..86b3c2f678 100644
--- a/packages/router-generator/tests/generator-fixture.ts
+++ b/packages/router-generator/tests/generator-fixture.ts
@@ -222,15 +222,26 @@ export async function prepareFixture(name: string, dir = fixtureDir(name)) {
join(dir, 'template.lazy.tsx'),
'utf8',
),
- 'bar.lazy.tsx': template,
+ // (a lazy file written with createFileRoute: its options are only
+ // what a lazy route takes, here a component)
+ 'bar.lazy.tsx': [
+ "import { createFileRoute } from '@tanstack/react-router'",
+ '',
+ "export const Route = createFileRoute('/foo/bar')({",
+ ' component: BarComponent,',
+ '})',
+ '',
+ 'function BarComponent() {',
+ ' return
Bar from its lazy file
',
+ '}',
+ '',
+ ].join('\n'),
'double-quotes.tsx': template.replace(
"createFileRoute('/foo/bar')",
'createFileRoute("/foo/bar")',
),
- 'template-literal.tsx': template.replace(
- "createFileRoute('/foo/bar')",
- 'createFileRoute(`/foo/bar`)',
- ),
+ // (a template literal id may be replaced or reported, SPEC J1.1:
+ // route-file-upkeep.test.ts)
'duplicate-import.tsx': [
"import { createFileRoute } from '@tanstack/react-router'",
"import * as React from 'react'",
diff --git a/packages/router-generator/tests/generator-fixtures.ts b/packages/router-generator/tests/generator-fixtures.ts
index b73fa9d365..cd8bdb26af 100644
--- a/packages/router-generator/tests/generator-fixtures.ts
+++ b/packages/router-generator/tests/generator-fixtures.ts
@@ -142,11 +142,6 @@ export const fixtureRoutes: Record> = {
'__root__',
'routes/(test)/initiallyLazy.tsx',
],
- '/(test)/template-literal': [
- '/template-literal',
- '__root__',
- 'routes/(test)/template-literal.tsx',
- ],
__root__: ['/', null, 'routes/__root.tsx'],
},
'flat-route-group': {
diff --git a/packages/router-generator/tests/generator.test.ts b/packages/router-generator/tests/generator.test.ts
index 3b691533c5..750eaa128f 100644
--- a/packages/router-generator/tests/generator.test.ts
+++ b/packages/router-generator/tests/generator.test.ts
@@ -82,6 +82,10 @@ async function postprocess(
expectOnlyOwnedEdits(source, written)
}
}
+ // (the lazy file switched to createLazyFileRoute gives the page)
+ await withRouteTree(config.generatedRouteTree, async ({ renderAt }) => {
+ expect(await renderAt('/bar')).toContain('Bar from its lazy file')
+ })
break
}
case 'custom-scaffolding': {
@@ -203,10 +207,7 @@ describe('generator fixtures', async () => {
await generator.run()
expect(fixtureRoutes[name], 'the routes of the fixture').toBeDefined()
- await expectFixtureRoutes(
- config.generatedRouteTree,
- fixtureRoutes[name]!,
- )
+ await expectFixtureRoutes(config.generatedRouteTree, fixtureRoutes[name]!)
await postprocess(name, config, before)
},
)
diff --git a/packages/router-generator/tests/owned-edits.test.ts b/packages/router-generator/tests/owned-edits.test.ts
index 8b0e08ff32..719789ae22 100644
--- a/packages/router-generator/tests/owned-edits.test.ts
+++ b/packages/router-generator/tests/owned-edits.test.ts
@@ -131,7 +131,10 @@ export const Route = createFileRoute('/old')({ component: () => Link })
test.each([
{
name: 'joining the router package import',
- after: withoutConstructor.replace('{ Link }', '{ Link, createFileRoute }'),
+ after: withoutConstructor.replace(
+ '{ Link }',
+ '{ Link, createFileRoute }',
+ ),
},
{
name: 'in an import of its own',
diff --git a/packages/router-generator/tests/route-file-upkeep.test.ts b/packages/router-generator/tests/route-file-upkeep.test.ts
index e0d70129a1..e9f841a8e7 100644
--- a/packages/router-generator/tests/route-file-upkeep.test.ts
+++ b/packages/router-generator/tests/route-file-upkeep.test.ts
@@ -13,7 +13,6 @@
* semicolons, line) is free.
*/
import path from 'node:path'
-import { parseSync } from 'vite'
import { afterEach, describe, expect, test, vi } from 'vitest'
import {
diagnosticsOf,
@@ -22,7 +21,7 @@ import {
import { createApp, generate, read, rootRoute } from './app'
import { expectOnlyOwnedEdits } from './owned-edits'
import { routeCallOf } from './route-id'
-import { evaluateModule, routesOf } from './route-tree'
+import { evaluateModule, routesOf, withRouteTree } from './route-tree'
import type { Config } from '../src'
afterEach(() => {
@@ -33,8 +32,9 @@ const routerPackage = '@tanstack/react-router'
const router = `'${routerPackage}'`
/**
- * Runs the generator on an app with a root route and `src/routes/`
- * holding `source`. Returns the file as the generator left it, the route
+ * Runs the generator on an app with a root route, `src/routes/`
+ * holding `source` and `otherFiles` (paths relative to the app root).
+ * Returns the file as the generator left it, the route
* tree's routes (route id to file) and the warnings; or the error of a run
* that fails.
*/
@@ -42,6 +42,7 @@ async function upkeep(
file: string,
source: string,
config: Partial = {},
+ otherFiles: Record = {},
) {
const warnings: Array = []
vi.spyOn(console, 'warn').mockImplementation((...args) => {
@@ -52,6 +53,7 @@ async function upkeep(
const root = await createApp({
'src/routes/__root.tsx': rootRoute(),
[`src/routes/${file}`]: source,
+ ...otherFiles,
})
let error: Error | undefined
let routes: Record | undefined
@@ -74,23 +76,13 @@ async function upkeep(
}
}
-/** The local names of the values a module imports from the router package. */
-function routerValueImports(code: string) {
- const { module } = parseSync('route.tsx', code)
- return module.staticImports
- .filter((statement) => statement.moduleRequest.value === routerPackage)
- .flatMap((statement) =>
- statement.entries
- .filter((entry) => !entry.isType)
- .map((entry) => entry.localName.value),
- )
-}
-
/**
* Asserts the upkeep of a route file written from `source`: it evaluates
- * with the real router, its Route is created with `createdWith` and `id`,
- * which it binds once from the router package, and it changed only where
- * the generator may edit it (owned-edits.ts).
+ * with the real router (a binding declared twice does not), its Route is
+ * a route of the router package's kind for `createdWith`, created with
+ * `createdWith` (bound to the router package export under any local name or
+ * through a namespace import) and `id`, and it changed only where the
+ * generator may edit it (owned-edits.ts).
*/
async function expectRouteFile(
written: string,
@@ -106,14 +98,19 @@ async function expectRouteFile(
fileName?: string
},
) {
- await evaluateModule(written, fileName)
+ const { exports, router: routerExports } = await evaluateModule(
+ written,
+ fileName,
+ )
+ expect(exports.Route).toBeInstanceOf(
+ createdWith === 'createLazyFileRoute'
+ ? routerExports!.LazyRoute
+ : routerExports!.Route,
+ )
expect(routeCallOf(written, fileName)).toEqual({
constructor: createdWith,
id,
})
- expect(
- routerValueImports(written).filter((name) => name === createdWith),
- ).toHaveLength(1)
expectOnlyOwnedEdits(source, written, fileName)
}
@@ -131,10 +128,7 @@ describe('route ids the generator fixes', () => {
name: 'a double-quoted id',
call: `createFileRoute("/old")({ component: Page })`,
},
- {
- name: 'a template literal id',
- call: 'createFileRoute(`/old`)({ component: Page })',
- },
+ // (a template literal id: replaced or reported, below)
])('a route file with $name gets its id fixed', async ({ call }) => {
const source = `import { createFileRoute } from ${router}
@@ -497,30 +491,78 @@ export const Route = createFileRoute('/old')({})`,
})
describe('route files the generator does not rewrite', () => {
+ // The route comes from an app module (excluded from routing by its `-`
+ // prefix) the generator does not keep up: the route file is left as it
+ // is and its route is registered, or the file is reported by name.
test.each([
{
name: 'a Route from another module',
source: `import { postsRoute } from './-posts-route'
export const Route = postsRoute
`,
+ helper: [
+ 'src/routes/-posts-route.tsx',
+ `import { createFileRoute } from ${router}
+
+export const postsRoute = createFileRoute('/new')({
+ component: () => 'new page',
+})
+`,
+ ],
},
{
name: 'a Route made by a route factory of the app',
source: `import { makeRoute } from './-make-route'
-export const Route = makeRoute()({})
+export const Route = makeRoute()({ component: () => 'new page' })
`,
- },
- ])('$name is left as it is', async ({ source }) => {
- const { written } = await upkeep('new.tsx', source)
+ helper: [
+ 'src/routes/-make-route.tsx',
+ `import { createFileRoute } from ${router}
- expect(written).toBe(source)
- })
+export const makeRoute = () => createFileRoute('/new')
+`,
+ ],
+ },
+ ])(
+ '$name is left as it is and registered, or reported by name',
+ async ({ source, helper: [helperFile, helperSource] }) => {
+ const { root, file, written, routes, warnings, error } = await upkeep(
+ 'new.tsx',
+ source,
+ {},
+ { [helperFile]: helperSource },
+ )
+
+ expect(written).toBe(source)
+ expect(await read(root, helperFile)).toBe(helperSource)
+ if (routes?.['/new'] === 'routes/new.tsx') {
+ await withRouteTree(
+ path.join(root, 'src/routeTree.gen.ts'),
+ async ({ renderAt }) => {
+ expect(await renderAt('/new')).toContain('new page')
+ },
+ )
+ return
+ }
+ expectDiagnostic(
+ [...diagnosticsOf(error), ...diagnosticsOf(warnings, 'warning')],
+ { file, root },
+ )
+ },
+ )
// A route id that is not a string literal: replacing it with the right
// literal (everything else as owned-edits.ts allows) and an actionable
// diagnostic naming the file (a failed run or a warning; the file then
// stays as it is) are both correct (SPEC J1.1).
test.each([
+ {
+ name: 'a template literal id',
+ source: `import { createFileRoute } from ${router}
+const Page = () => null
+export const Route = createFileRoute(\`/old\`)({ component: Page })
+`,
+ },
{
name: 'an id read from a variable',
source: `import { createFileRoute } from ${router}
@@ -559,37 +601,61 @@ export const Route = createFileRoute(\`/\${x}\`)({})
},
)
- // A malformed route call: the user is told which file, by a failed run or
- // by a warning (the file then stays as it is).
+ // A malformed route call (a never-fail-silently control, not a supported
+ // input: the router's types reject options passed to the constructor
+ // directly, TS2345). Either the user is told which file, by a failed run
+ // or by a warning (the file then stays as it is), or the call is repaired
+ // into the curried call with the route's id, keeping its options.
test.each([
{
name: 'options passed to createFileRoute directly',
+ constructor: 'createFileRoute',
source: `import { createFileRoute } from ${router}
export const Route = createFileRoute({ component: () => null })
`,
},
{
name: 'options passed to createLazyFileRoute directly',
+ constructor: 'createLazyFileRoute',
fileName: 'new.lazy.tsx',
source: `import { createLazyFileRoute } from ${router}
export const Route = createLazyFileRoute({ component: () => null })
`,
},
- ])(
- 'a route file with $name is reported by name',
- async ({ source, fileName = 'new.tsx' }) => {
- const { root, file, written, warnings, error } = await upkeep(
+ ] as const)(
+ 'a route file with $name is reported by name or repaired',
+ async ({ source, constructor, fileName = 'new.tsx' }) => {
+ const { root, file, written, routes, warnings, error } = await upkeep(
fileName,
source,
)
+ if (!error && written !== source) {
+ // (repaired: the same file with the curried call, as far as the
+ // generator's edits go)
+ await expectRouteFile(written, {
+ id: '/new',
+ createdWith: constructor,
+ source: source.replace(
+ `${constructor}({`,
+ `${constructor}('/new')({`,
+ ),
+ fileName,
+ })
+ const { exports } = await evaluateModule(written, fileName)
+ expect(exports.Route.options.component()).toBeNull()
+ expect(routes).toEqual({
+ __root__: 'routes/__root.tsx',
+ // (a lazy-only route is created by the tree)
+ '/new':
+ constructor === 'createLazyFileRoute' ? null : 'routes/new.tsx',
+ })
+ return
+ }
expectDiagnostic(
[...diagnosticsOf(error), ...diagnosticsOf(warnings, 'warning')],
{ file, root },
)
- if (!error) {
- expect(written).toBe(source)
- }
},
)
})