vitestSetup.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import '@testing-library/jest-dom/vitest'
  2. import { cleanup } from '@testing-library/react'
  3. import dayjs from 'dayjs'
  4. import relativeTime from 'dayjs/plugin/relativeTime'
  5. import timezone from 'dayjs/plugin/timezone'
  6. import utc from 'dayjs/plugin/utc'
  7. import { createDynamicRouteParser } from 'next-router-mock/dist/dynamic-routes'
  8. import { afterAll, afterEach, beforeAll, vi } from 'vitest'
  9. import { mswServer } from './lib/msw'
  10. import { routerMock } from './lib/route-mock'
  11. dayjs.extend(utc)
  12. dayjs.extend(timezone)
  13. dayjs.extend(relativeTime)
  14. // Uncomment this if HTML in errors are being annoying.
  15. //
  16. // configure({
  17. // getElementError: (message, container) => {
  18. // const error = new Error(message ?? 'Element not found')
  19. // error.name = 'ElementNotFoundError'
  20. // return error
  21. // },
  22. // })
  23. beforeAll(() => {
  24. mswServer.listen({ onUnhandledRequest: `error` })
  25. vi.mock('next/router', () => require('next-router-mock'))
  26. vi.mock('next/navigation', async () => {
  27. const actual = await vi.importActual('next/navigation')
  28. return {
  29. ...actual,
  30. useRouter: () => {
  31. return {
  32. push: vi.fn(),
  33. replace: vi.fn(),
  34. }
  35. },
  36. usePathname: () => vi.fn(),
  37. useSearchParams: () => ({
  38. get: vi.fn(),
  39. }),
  40. }
  41. })
  42. vi.mock('next/compat/router', () => require('next-router-mock'))
  43. // Mock the useParams hook from common module globally
  44. vi.mock('common', async (importOriginal: any) => {
  45. const actual = await importOriginal()
  46. return {
  47. ...(typeof actual === 'object' ? actual : {}),
  48. useParams: () => ({ ref: 'default' }),
  49. }
  50. })
  51. routerMock.useParser(createDynamicRouteParser(['/projects/[ref]']))
  52. })
  53. afterEach(() => {
  54. mswServer.resetHandlers()
  55. cleanup()
  56. })
  57. afterAll(() => {
  58. mswServer.close()
  59. })