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