|
| 1 | +import { mount } from '../../helpers/test' |
| 2 | +import { ref } from '../../api' |
| 3 | +import { useTimeoutFn } from '../../vue-use-kit' |
| 4 | + |
| 5 | +beforeEach(() => { |
| 6 | + jest.useFakeTimers() |
| 7 | +}) |
| 8 | + |
| 9 | +afterEach(() => { |
| 10 | + jest.clearAllTimers() |
| 11 | +}) |
| 12 | + |
| 13 | +const testComponent = () => ({ |
| 14 | + template: ` |
| 15 | + <div> |
| 16 | + <div id="isReady" v-if="isReady"> |
| 17 | + <button id="cancelTimer" @click="cancelTimer"></button> |
| 18 | + <button id="resetTimer" @click="resetTimer"></button> |
| 19 | + <div id="isCallbackCalled" v-if="isCallbackCalled"></div> |
| 20 | + </div> |
| 21 | + </div> |
| 22 | + `, |
| 23 | + setup() { |
| 24 | + const isCallbackCalled = ref(false) |
| 25 | + const { isReady, cancelTimer, resetTimer } = useTimeoutFn(() => { |
| 26 | + isCallbackCalled.value = true |
| 27 | + }, 1000) |
| 28 | + return { isReady, cancelTimer, resetTimer, isCallbackCalled } |
| 29 | + } |
| 30 | +}) |
| 31 | + |
1 | 32 | describe('useTimeoutFn', () => { |
2 | | - it('should do something', () => { |
3 | | - // Add test here |
| 33 | + it('should call setTimeout when initialized', () => { |
| 34 | + expect(setTimeout).toHaveBeenCalledTimes(0) |
| 35 | + mount(testComponent()) |
| 36 | + expect(setTimeout).toHaveBeenCalledTimes(1) |
| 37 | + }) |
| 38 | + |
| 39 | + it('should call setTimeout again when resetTimer is called', async () => { |
| 40 | + expect(setTimeout).toHaveBeenCalledTimes(0) |
| 41 | + const wrapper = mount(testComponent()) |
| 42 | + expect(setTimeout).toHaveBeenCalledTimes(1) |
| 43 | + jest.runAllTimers() |
| 44 | + |
| 45 | + // Vue is inserting #resetTimer in the DOM |
| 46 | + await wrapper.vm.$nextTick() |
| 47 | + wrapper.find('#resetTimer').trigger('click') |
| 48 | + expect(setTimeout).toHaveBeenCalledTimes(2) |
| 49 | + }) |
| 50 | + |
| 51 | + it('should hide all elements when cancelTimer is called', async () => { |
| 52 | + const wrapper = mount(testComponent()) |
| 53 | + jest.runAllTimers() |
| 54 | + |
| 55 | + // Vue is inserting #isReady in the DOM |
| 56 | + await wrapper.vm.$nextTick() |
| 57 | + expect(wrapper.find('#isReady').exists()).toBe(true) |
| 58 | + wrapper.find('#cancelTimer').trigger('click') |
| 59 | + jest.runAllTimers() |
| 60 | + |
| 61 | + // Vue is removing #isReady from the DOM |
| 62 | + await wrapper.vm.$nextTick() |
| 63 | + expect(wrapper.find('#isReady').exists()).toBe(false) |
| 64 | + }) |
| 65 | + |
| 66 | + it('should display #isReady when the timers are called', async () => { |
| 67 | + const wrapper = mount(testComponent()) |
| 68 | + jest.runAllTimers() |
| 69 | + |
| 70 | + // Vue is inserting #isReady in the DOM |
| 71 | + await wrapper.vm.$nextTick() |
| 72 | + expect(wrapper.find('#isReady').exists()).toBe(true) |
4 | 73 | }) |
5 | 74 | }) |
0 commit comments