Skip to content

Commit

Permalink
feat: add useLifecycles
Browse files Browse the repository at this point in the history
  • Loading branch information
lmhcoding committed Sep 20, 2020
1 parent 2f3c6db commit b19dd8d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/index.ts
Expand Up @@ -10,3 +10,4 @@ export * from './useBoolean'
export * from './useStorage'
export * from './useLocalStorage'
export * from './useStorage'
export * from './useLifecycles'
12 changes: 12 additions & 0 deletions src/useLifecycles.ts
@@ -0,0 +1,12 @@
import { getCurrentInstance, onMounted, onUnmounted } from 'vue'

interface Callback {
(): any
}

export function useLifecycles(mountedCb: Callback, unmountCb: Callback): void {
if (getCurrentInstance()) {
mountedCb && onMounted(mountedCb)
unmountCb && onUnmounted(unmountCb)
}
}
18 changes: 18 additions & 0 deletions tests/useLifecycles.test.ts
@@ -0,0 +1,18 @@
import { mount } from '@vue/test-utils'
import { useLifecycles } from '../src/useLifecycles'

describe('test useLifecycles', () => {
test('callback should be called when mounted or unmounted', () => {
const onMounted = jest.fn()
const onUnmounted = jest.fn()
const wrapper = mount({
template: '<div>test</div>',
setup () {
useLifecycles(onMounted, onUnmounted)
}
})
expect(onMounted).toHaveBeenCalledTimes(1)
wrapper.unmount()
expect(onUnmounted).toHaveBeenCalledTimes(1)
})
})

0 comments on commit b19dd8d

Please sign in to comment.