raf.test.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /* eslint-disable import/first */
  2. let isClientMocked = false
  3. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  4. import { cAF, rAF } from '..'
  5. vi.mock('@vueuse/core', () => ({
  6. get isClient() {
  7. return isClientMocked
  8. },
  9. }))
  10. describe('raf', () => {
  11. beforeEach(() => {
  12. vi.useFakeTimers()
  13. })
  14. afterEach(() => {
  15. vi.useRealTimers()
  16. vi.restoreAllMocks()
  17. })
  18. it('CSR should work', () => {
  19. isClientMocked = true
  20. const fn = vi.fn()
  21. rAF(() => fn('first'))
  22. vi.runAllTimers()
  23. expect(fn.mock.calls).toMatchInlineSnapshot(`
  24. [
  25. [
  26. "first",
  27. ],
  28. ]
  29. `)
  30. rAF(() => fn('second'))
  31. vi.runAllTimers()
  32. expect(fn.mock.calls).toMatchInlineSnapshot(`
  33. [
  34. [
  35. "first",
  36. ],
  37. [
  38. "second",
  39. ],
  40. ]
  41. `)
  42. const handle = rAF(() => fn('cancel'))
  43. cAF(handle)
  44. vi.runAllTimers()
  45. expect(fn.mock.calls).toMatchInlineSnapshot(`
  46. [
  47. [
  48. "first",
  49. ],
  50. [
  51. "second",
  52. ],
  53. ]
  54. `)
  55. })
  56. it('SSR should work', () => {
  57. isClientMocked = false
  58. const fn = vi.fn()
  59. rAF(() => fn('first'))
  60. vi.runAllTimers()
  61. expect(fn.mock.calls).toMatchInlineSnapshot(`
  62. [
  63. [
  64. "first",
  65. ],
  66. ]
  67. `)
  68. rAF(() => fn('second'))
  69. vi.runAllTimers()
  70. expect(fn.mock.calls).toMatchInlineSnapshot(`
  71. [
  72. [
  73. "first",
  74. ],
  75. [
  76. "second",
  77. ],
  78. ]
  79. `)
  80. const handle = rAF(() => fn('cancel'))
  81. cAF(handle)
  82. vi.runAllTimers()
  83. expect(fn.mock.calls).toMatchInlineSnapshot(`
  84. [
  85. [
  86. "first",
  87. ],
  88. [
  89. "second",
  90. ],
  91. ]
  92. `)
  93. })
  94. })