mirror of
https://gitee.com/element-plus/element-plus.git
synced 2024-12-02 11:17:46 +08:00
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:
parent
1989eed7f0
commit
6b4c04fd0a
56
packages/hooks/__tests__/use-timeout.spec.ts
Normal file
56
packages/hooks/__tests__/use-timeout.spec.ts
Normal 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()
|
||||
})
|
||||
})
|
@ -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'
|
||||
|
20
packages/hooks/use-timeout/index.ts
Normal file
20
packages/hooks/use-timeout/index.ts
Normal 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)
|
||||
},
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user