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

useMatch.test-d.tsx

79 lines2.1 KB

1import { describe, expectTypeOf, test } from 'vitest'
2import { createRootRoute, createRoute, createRouter, useMatch } from '../src'
3import type { MakeRouteMatch, MakeRouteMatchUnion } from '@tanstack/router-core'
4​
5const rootRoute = createRootRoute()
6​
7const indexRoute = createRoute({
8 getParentRoute: () => rootRoute,
9 path: '/',
10})
11​
12const invoicesRoute = createRoute({
13 getParentRoute: () => rootRoute,
14 path: 'invoices',
15})
16​
17const routeTree = rootRoute.addChildren([invoicesRoute, indexRoute])
18​
19// eslint-disable-next-line unused-imports/no-unused-vars
20const defaultRouter = createRouter({ routeTree })
21​
22type DefaultRouter = typeof defaultRouter
23​
24type TRouteMatch = MakeRouteMatch<DefaultRouter['routeTree']>
25​
26describe('useMatch', () => {
27 describe('shouldThrow', () => {
28 const from = '/invoices'
29 test('return type is `RouteMatch` when shouldThrow = true', () => {
30 const shouldThrow = true
31 const match = useMatch<
32 DefaultRouter,
33 typeof from,
34 true, // TStrict
35 typeof shouldThrow,
36 TRouteMatch
37 >({ from, shouldThrow })
38​
39 expectTypeOf(match).toEqualTypeOf<TRouteMatch>()
40 })
41​
42 test('return type is `RouteMatch | undefined` when shouldThrow = false', () => {
43 const shouldThrow = false
44 const match = useMatch<
45 DefaultRouter,
46 typeof from,
47 true, // TStrict
48 typeof shouldThrow,
49 TRouteMatch
50 >({ from, shouldThrow })
51​
52 expectTypeOf(match).toEqualTypeOf<TRouteMatch | undefined>()
53 })
54 })
55​
56 test('return type is union of matches when strict = false', () => {
57 const strict = false as const
58 const match = useMatch<DefaultRouter, typeof undefined, typeof strict>({
59 strict,
60 })
61​
62 expectTypeOf(match).toEqualTypeOf<MakeRouteMatchUnion<DefaultRouter>>()
63 })
64​
65 test('shouldThrow must be false when strict is false', () => {
66 const strict = false as const
67 const shouldThrow = true as const
68 useMatch<
69 DefaultRouter,
70 typeof undefined,
71 typeof strict,
72 typeof shouldThrow
73 >({
74 strict,
75 // @ts-expect-error shouldThrow must be false when strict is false
76 shouldThrow,
77 })
78 })
79})