From e83a18ea27c7a29ffb2eb92d3a2e3fbb145a6119 Mon Sep 17 00:00:00 2001 From: wzc520pyfm <1528857653@qq.com> Date: Mon, 15 Apr 2024 18:03:02 +0800 Subject: [PATCH] test(hooks): add use-throttle-render test (#16499) * test(hooks): add use-throttle-render test * chore(hooks): [use-throttle-render] fix lint err * chore(hooks): use sleep and concurrent * fix(hooks): [use-throttle-render] fix import error * fix(hooks): fix concurrent interfere --- .../__tests__/use-throttle-render.test.tsx | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 packages/hooks/__tests__/use-throttle-render.test.tsx diff --git a/packages/hooks/__tests__/use-throttle-render.test.tsx b/packages/hooks/__tests__/use-throttle-render.test.tsx new file mode 100644 index 0000000000..500181b639 --- /dev/null +++ b/packages/hooks/__tests__/use-throttle-render.test.tsx @@ -0,0 +1,50 @@ +import { defineComponent, nextTick, ref } from 'vue' +import { mount } from '@vue/test-utils' +import { describe, expect, it } from 'vitest' +import sleep from '@element-plus/test-utils/sleep' +import { useThrottleRender } from '../use-throttle-render' + +const Comp = defineComponent({ + setup() { + const loading = ref(false) + const throttled = useThrottleRender(loading, 1000) + // Test the settimeout branch clearly: trigger the watch to record the settimeout first, and then record the settimeout again when mount. + loading.value = true + + return () =>
{throttled.value.toString()}
+ }, +}) + +describe.concurrent('useThrottleRender', () => { + it('should throttle rendering when loading is true', async () => { + const wrapper = mount(Comp) + await nextTick() + expect(wrapper.find('.test-dom').text()).toBe('false') // initially false + await sleep(1000) + expect(wrapper.find('.test-dom').text()).toBe('true') // after throttle time, should be true + wrapper.unmount() + }) + + it('should return false immediately when loading is false', () => { + const loading = ref(false) + const throttled = useThrottleRender(loading, 1000) + expect(throttled.value).toBe(false) + }) + + it('should return the same value immediately when throttle is 0', () => { + const loading = ref(true) + const throttled = useThrottleRender(loading, 0) + expect(throttled.value).toBe(true) // should be same as loading + }) + + it('should throttle rendering and update when loading changes', async () => { + const loading = ref(true) + const throttled = useThrottleRender(loading, 1000) + expect(throttled.value).toBe(false) // initially false + loading.value = false + expect(throttled.value).toBe(false) // should remain false immediately + await sleep(1000) + loading.value = true + expect(throttled.value).toBe(false) // should still be false after throttle time + }) +})