setup.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { vi, beforeEach } from 'vitest'
  2. /**
  3. * In-memory store for uni mocked storage APIs.
  4. * Cleared between tests via beforeEach.
  5. * Exposed as uni.__mockStorage so tests can pre-populate storage values
  6. * before store creation (e.g. simulating a saved token).
  7. */
  8. const mockStorage = {}
  9. /**
  10. * Mock all uni-app APIs used by stores and common pages.
  11. *
  12. * The storage mocks (getStorageSync / setStorageSync / removeStorageSync)
  13. * operate on the mockStorage object above, which persists across calls
  14. * within a test but is wiped before each test.
  15. *
  16. * Tests can push values into storage by setting:
  17. * uni.__mockStorage.theme = 'light'
  18. * uni.__mockStorage.token = 'my-token'
  19. */
  20. globalThis.uni = {
  21. /** Storage — backed by mockStorage */
  22. getStorageSync: vi.fn((key) => mockStorage[key]),
  23. setStorageSync: vi.fn((key, value) => { mockStorage[key] = value }),
  24. removeStorageSync: vi.fn((key) => { delete mockStorage[key] }),
  25. /** System info */
  26. getSystemInfoSync: vi.fn(() => ({ theme: 'dark' })),
  27. onThemeChange: vi.fn(),
  28. /** Tab bar */
  29. setTabBarStyle: vi.fn(),
  30. /** Navigation */
  31. getCurrentPages: vi.fn(() => []),
  32. navigateTo: vi.fn(),
  33. reLaunch: vi.fn(),
  34. /** Feedback */
  35. showModal: vi.fn(),
  36. showToast: vi.fn(),
  37. /** Network */
  38. request: vi.fn(),
  39. downloadFile: vi.fn(),
  40. uploadFile: vi.fn(),
  41. /** Exposed for test convenience */
  42. __mockStorage: mockStorage,
  43. }
  44. // ── Per-test cleanup ─────────────────────────────────────────────
  45. beforeEach(() => {
  46. // Wipe the in-memory storage so no state leaks between tests
  47. Object.keys(mockStorage).forEach((k) => delete mockStorage[k])
  48. // Reset call history and custom return-values for all vi.fn() mocks
  49. // (implementations provided in the factory are *not* removed)
  50. vi.clearAllMocks()
  51. })