|
| 1 | +import { useTimeout } from "../../src"; |
| 2 | +import { createVue } from "../utils"; |
| 3 | +import { Ref, ref } from "../../src/api"; |
| 4 | + |
| 5 | +describe("timeout", () => { |
| 6 | + jest.useFakeTimers(); |
| 7 | + it("should be defined", () => { |
| 8 | + expect(useTimeout).toBeDefined(); |
| 9 | + }); |
| 10 | + |
| 11 | + it("should call passed function after given amount of time", async () => { |
| 12 | + let count = 0; |
| 13 | + useTimeout(() => { |
| 14 | + count++; |
| 15 | + }, 1000); |
| 16 | + |
| 17 | + expect(count).toBe(0); |
| 18 | + jest.advanceTimersByTime(900); |
| 19 | + // should not be resolved |
| 20 | + expect(count).toBe(0); |
| 21 | + |
| 22 | + jest.advanceTimersByTime(100); |
| 23 | + expect(count).toBe(1); |
| 24 | + }); |
| 25 | + |
| 26 | + it("should set ready true after run callback", async () => { |
| 27 | + const { ready } = useTimeout(() => {}, 1000); |
| 28 | + |
| 29 | + expect(ready.value).toBe(false); |
| 30 | + jest.advanceTimersByTime(1000); |
| 31 | + expect(ready.value).toBe(true); |
| 32 | + }); |
| 33 | + |
| 34 | + it("should cancel function call when call cancel function", async () => { |
| 35 | + let count = 0; |
| 36 | + const { ready, cancel } = useTimeout(() => { |
| 37 | + count++; |
| 38 | + }, 1000); |
| 39 | + |
| 40 | + expect(ready.value).toBe(false); |
| 41 | + expect(count).toBe(0); |
| 42 | + |
| 43 | + cancel(); |
| 44 | + |
| 45 | + jest.advanceTimersByTime(1000); |
| 46 | + expect(ready.value).toBe(null); |
| 47 | + expect(count).toBe(0); |
| 48 | + }); |
| 49 | + |
| 50 | + it("should cancel on unMounted", async () => { |
| 51 | + let ready: Ref<boolean | null> = ref(false); |
| 52 | + |
| 53 | + const { mount, destroy } = createVue({ |
| 54 | + template: `<div></div>`, |
| 55 | + setup() { |
| 56 | + ready = useTimeout(() => {}, 1000).ready; |
| 57 | + }, |
| 58 | + }); |
| 59 | + |
| 60 | + mount(); |
| 61 | + |
| 62 | + expect(ready.value).toBe(false); |
| 63 | + jest.advanceTimersByTime(500); |
| 64 | + expect(ready.value).toBe(false); |
| 65 | + |
| 66 | + destroy(); |
| 67 | + expect(ready.value).toBe(null); |
| 68 | + }); |
| 69 | + |
| 70 | + it("should default the delay to 0", () => { |
| 71 | + let count = 0; |
| 72 | + useTimeout(() => { |
| 73 | + count++; |
| 74 | + }); |
| 75 | + |
| 76 | + expect(count).toBe(0); |
| 77 | + jest.runOnlyPendingTimers(); |
| 78 | + expect(count).toBe(1); |
| 79 | + }); |
| 80 | +}); |
0 commit comments