route-mock.ts26 lines · main
1import { glob } from 'fs/promises'
2import { join, normalize, posix, sep } from 'path'
3import _routerMock from 'next-router-mock'
4import { createDynamicRouteParser } from 'next-router-mock/dynamic-routes'
5
6export const routerMock = _routerMock
7
8const pipe =
9 <T>(...fns: Array<(arg: T) => T>) =>
10 (value: T) =>
11 fns.reduce((acc, fn) => fn(acc), value)
12// normalize file paths to posix format (windows FS support)
13const toPosix = (str: string) => str.replaceAll(sep, posix.sep)
14const pagesRoot = toPosix(join(process.cwd(), `./pages`))
15// remove the base filepath
16const removePrefix = (str: string) => str.replace(pagesRoot, ``)
17// remove the file extension or index segment
18const removeExt = (str: string) => str.replace(/.tsx|\/index.tsx/, ``)
19
20// Glob the `pages/` directory for all dynamic route segments
21const paths = [
22 ...(await Array.fromAsync(glob(`${pagesRoot}/**/*\].tsx`))),
23 ...(await Array.fromAsync(glob(`${pagesRoot}/**/**\]/**/index.tsx`))),
24].map(pipe(normalize, toPosix, removePrefix, removeExt))
25
26routerMock.useParser(createDynamicRouteParser(paths))