feat(hooks): add use-timeout hook (#2439)

* feat(hooks): add use-timeout hook

- Add use timeout hook for register timeout callbacks
- Add test cases against add-timeout

* resolve linter issue
This commit is contained in:
jeremywu 2021-07-06 07:49:49 +08:00 committed by GitHub
parent 1989eed7f0
commit 6b4c04fd0a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 77 additions and 0 deletions

View File

@ -0,0 +1,56 @@
import { mount } from '@vue/test-utils'
import useTimeout from '../use-timeout'
const _mount = (cb: () => void) => {
return mount({
setup() {
const { cancelTimeout, registerTimeout } = useTimeout()
registerTimeout(cb, 0)
return {
cancelTimeout,
}
},
render() {
return null
},
})
}
jest.useFakeTimers()
describe('use-timeout', () => {
let wrapper
const cb = jest.fn()
beforeEach(() => {
cb.mockClear()
wrapper = _mount(cb)
})
it('should register timeout correctly', async () => {
expect(cb).not.toHaveBeenCalled()
jest.runOnlyPendingTimers()
expect(cb).toHaveBeenCalled()
wrapper.unmount()
})
it('should cancel the timeout correctly', async () => {
wrapper.vm.cancelTimeout()
jest.runOnlyPendingTimers()
expect(cb).not.toHaveBeenCalled()
wrapper.unmount()
})
it('should cancel timeout before unmount', () => {
expect(cb).not.toHaveBeenCalled()
wrapper.unmount()
jest.runOnlyPendingTimers()
expect(cb).not.toHaveBeenCalled()
})
})

View File

@ -8,4 +8,5 @@ export { default as useFocus } from './use-focus'
export { default as useThrottleRender } from './use-throttle-render'
export { default as usePreventGlobal } from './use-prevent-global'
export { default as useTeleport } from './use-teleport'
export { default as useTimeout } from './use-timeout'
export * from './use-model-toggle'

View File

@ -0,0 +1,20 @@
import { onBeforeUnmount } from 'vue'
export default function () {
let timeoutHandle: ReturnType<typeof setTimeout>
onBeforeUnmount(() => {
clearTimeout(timeoutHandle)
})
return {
registerTimeout: (fn: (...args: any[]) => unknown, delay: number) => {
clearTimeout(timeoutHandle)
timeoutHandle = setTimeout(fn, delay)
},
cancelTimeout: () => {
clearTimeout(timeoutHandle)
},
}
}