use-timeout.test.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { mount } from '@vue/test-utils'
  2. import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
  3. import { useTimeout } from '../use-timeout'
  4. const _mount = (cb: () => void) => {
  5. return mount({
  6. setup() {
  7. const { cancelTimeout, registerTimeout } = useTimeout()
  8. registerTimeout(cb, 0)
  9. return { cancelTimeout }
  10. },
  11. render: () => undefined,
  12. })
  13. }
  14. describe('use-timeout', () => {
  15. beforeEach(() => {
  16. vi.useFakeTimers()
  17. wrapper = _mount(cb)
  18. })
  19. afterEach(() => {
  20. vi.restoreAllMocks()
  21. })
  22. let wrapper: ReturnType<typeof _mount>
  23. const cb = vi.fn()
  24. it('should register timeout correctly', async () => {
  25. expect(cb).not.toHaveBeenCalled()
  26. vi.runOnlyPendingTimers()
  27. expect(cb).toHaveBeenCalled()
  28. wrapper.unmount()
  29. })
  30. it('should cancel the timeout correctly', async () => {
  31. wrapper.vm.cancelTimeout()
  32. vi.runOnlyPendingTimers()
  33. expect(cb).not.toHaveBeenCalled()
  34. wrapper.unmount()
  35. })
  36. it('should cancel timeout before unmount', () => {
  37. expect(cb).not.toHaveBeenCalled()
  38. wrapper.unmount()
  39. vi.runOnlyPendingTimers()
  40. expect(cb).not.toHaveBeenCalled()
  41. })
  42. })