2021-07-06 07:49:49 +08:00
|
|
|
import { mount } from '@vue/test-utils'
|
2022-03-25 15:35:56 +08:00
|
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
2021-11-29 15:58:44 +08:00
|
|
|
import { useTimeout } from '../use-timeout'
|
2021-07-06 07:49:49 +08:00
|
|
|
|
|
|
|
const _mount = (cb: () => void) => {
|
|
|
|
return mount({
|
|
|
|
setup() {
|
|
|
|
const { cancelTimeout, registerTimeout } = useTimeout()
|
|
|
|
registerTimeout(cb, 0)
|
|
|
|
|
2022-02-21 14:28:22 +08:00
|
|
|
return { cancelTimeout }
|
2021-07-06 07:49:49 +08:00
|
|
|
},
|
2022-02-21 14:28:22 +08:00
|
|
|
render: () => undefined,
|
2021-07-06 07:49:49 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
describe('use-timeout', () => {
|
|
|
|
beforeEach(() => {
|
2022-02-21 14:28:22 +08:00
|
|
|
vi.useFakeTimers()
|
2021-07-06 07:49:49 +08:00
|
|
|
wrapper = _mount(cb)
|
|
|
|
})
|
2022-02-21 14:28:22 +08:00
|
|
|
afterEach(() => {
|
|
|
|
vi.restoreAllMocks()
|
|
|
|
})
|
|
|
|
|
|
|
|
let wrapper: ReturnType<typeof _mount>
|
|
|
|
const cb = vi.fn()
|
2021-07-06 07:49:49 +08:00
|
|
|
|
|
|
|
it('should register timeout correctly', async () => {
|
|
|
|
expect(cb).not.toHaveBeenCalled()
|
2022-02-21 14:28:22 +08:00
|
|
|
vi.runOnlyPendingTimers()
|
2021-07-06 07:49:49 +08:00
|
|
|
expect(cb).toHaveBeenCalled()
|
|
|
|
wrapper.unmount()
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should cancel the timeout correctly', async () => {
|
|
|
|
wrapper.vm.cancelTimeout()
|
|
|
|
|
2022-02-21 14:28:22 +08:00
|
|
|
vi.runOnlyPendingTimers()
|
2021-07-06 07:49:49 +08:00
|
|
|
|
|
|
|
expect(cb).not.toHaveBeenCalled()
|
|
|
|
wrapper.unmount()
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should cancel timeout before unmount', () => {
|
|
|
|
expect(cb).not.toHaveBeenCalled()
|
|
|
|
|
|
|
|
wrapper.unmount()
|
2022-02-21 14:28:22 +08:00
|
|
|
vi.runOnlyPendingTimers()
|
2021-07-06 07:49:49 +08:00
|
|
|
|
|
|
|
expect(cb).not.toHaveBeenCalled()
|
|
|
|
})
|
|
|
|
})
|