route-mock.ts 1.1 KB

1234567891011121314151617181920212223242526
  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. export const routerMock = _routerMock
  6. const pipe =
  7. <T>(...fns: Array<(arg: T) => T>) =>
  8. (value: T) =>
  9. fns.reduce((acc, fn) => fn(acc), value)
  10. // normalize file paths to posix format (windows FS support)
  11. const toPosix = (str: string) => str.replaceAll(sep, posix.sep)
  12. const pagesRoot = toPosix(join(process.cwd(), `./pages`))
  13. // remove the base filepath
  14. const removePrefix = (str: string) => str.replace(pagesRoot, ``)
  15. // remove the file extension or index segment
  16. const removeExt = (str: string) => str.replace(/.tsx|\/index.tsx/, ``)
  17. // Glob the `pages/` directory for all dynamic route segments
  18. const paths = [
  19. ...(await Array.fromAsync(glob(`${pagesRoot}/**/*\].tsx`))),
  20. ...(await Array.fromAsync(glob(`${pagesRoot}/**/**\]/**/index.tsx`))),
  21. ].map(pipe(normalize, toPosix, removePrefix, removeExt))
  22. routerMock.useParser(createDynamicRouteParser(paths))