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 99286f8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/useLifecycles.ts
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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 99286f8

Please sign in to comment.