|
| 1 | +import { act, renderHook } from "@testing-library/react"; |
| 2 | +import { useTextSelection, getRangesSelection } from "./useTextSelection"; |
| 3 | + |
| 4 | +const mockGetBoundingClientRect = vi.fn(); |
| 5 | + |
| 6 | +it("Should return initial selecition state", () => { |
| 7 | + const selection = window.getSelection(); |
| 8 | + |
| 9 | + const { result } = renderHook(() => useTextSelection()); |
| 10 | + |
| 11 | + expect(result.current.selection).toBe(selection); |
| 12 | + expect(result.current.text).toBe(selection?.toString() ?? ""); |
| 13 | + expect(result.current.ranges).toEqual( |
| 14 | + selection ? getRangesSelection(selection) : [] |
| 15 | + ); |
| 16 | +}); |
| 17 | + |
| 18 | +it("Should handle selection change", () => { |
| 19 | + const { result } = renderHook(() => useTextSelection()); |
| 20 | + |
| 21 | + const range = document.createRange(); |
| 22 | + const textNode = document.createTextNode("hello_world"); |
| 23 | + document.body.appendChild(textNode); |
| 24 | + |
| 25 | + range.selectNodeContents(textNode); |
| 26 | + |
| 27 | + range.getBoundingClientRect = mockGetBoundingClientRect; |
| 28 | + |
| 29 | + const selection = window.getSelection()!; |
| 30 | + |
| 31 | + act(() => { |
| 32 | + selection.removeAllRanges(); |
| 33 | + selection.addRange(range); |
| 34 | + document.dispatchEvent(new Event("selectionchange")); |
| 35 | + }); |
| 36 | + |
| 37 | + expect(result.current.text).toBe("hello_world"); |
| 38 | + expect(result.current.ranges.length).toBe(1); |
| 39 | + expect(result.current.rects.length).toBe(1); |
| 40 | +}); |
| 41 | + |
| 42 | +it("Should add and remove selectionchange listener", () => { |
| 43 | + const addSpy = vi.spyOn(document, "addEventListener"); |
| 44 | + const removeSpy = vi.spyOn(document, "removeEventListener"); |
| 45 | + |
| 46 | + const { unmount } = renderHook(() => useTextSelection()); |
| 47 | + |
| 48 | + expect(addSpy).toHaveBeenCalledWith("selectionchange", expect.any(Function)); |
| 49 | + |
| 50 | + unmount(); |
| 51 | + |
| 52 | + expect(removeSpy).toHaveBeenCalledWith( |
| 53 | + "selectionchange", |
| 54 | + expect.any(Function) |
| 55 | + ); |
| 56 | +}); |
0 commit comments