From 6a89239a7554e3bdd65d8338590cfebe0c87ba90 Mon Sep 17 00:00:00 2001 From: robonen Date: Sun, 6 Oct 2024 21:07:29 +0700 Subject: [PATCH] test(packages/vue): add test for tryOnMounted --- .../composables/tryOnMounted/index.test.ts | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 packages/vue/src/composables/tryOnMounted/index.test.ts diff --git a/packages/vue/src/composables/tryOnMounted/index.test.ts b/packages/vue/src/composables/tryOnMounted/index.test.ts new file mode 100644 index 0000000..a45920e --- /dev/null +++ b/packages/vue/src/composables/tryOnMounted/index.test.ts @@ -0,0 +1,59 @@ +import { describe, it, vi, expect } from 'vitest'; +import { defineComponent, nextTick, type PropType } from 'vue'; +import { tryOnMounted } from '.'; +import { mount } from '@vue/test-utils'; + +const ComponentStub = defineComponent({ + props: { + callback: { + type: Function as PropType<() => void>, + required: true, + }, + }, + setup(props) { + tryOnMounted(props.callback); + }, + template: `
`, +}); + +describe('tryOnMounted', () => { + it('should run the callback when mounted', () => { + const callback = vi.fn(); + + mount(ComponentStub, { + props: { callback }, + }); + + expect(callback).toHaveBeenCalled(); + }); + + it('should run the callback outside of a component lifecycle', () => { + const callback = vi.fn(); + + tryOnMounted(callback); + + expect(callback).toHaveBeenCalled(); + }); + + it('should run the callback asynchronously', async () => { + const callback = vi.fn(); + + tryOnMounted(callback, { sync: false }); + + expect(callback).not.toHaveBeenCalled(); + await nextTick(); + expect(callback).toHaveBeenCalled(); + }); + + it('should run the callback with a specific target', () => { + const callback = vi.fn(); + + const component = mount(ComponentStub, { + props: { callback: () => {} }, + }); + + tryOnMounted(callback, { target: component.vm.$ }); + + expect(callback).toHaveBeenCalled(); + }); +}); \ No newline at end of file