|
1 | | -import { render } from "@testing-library/react"; |
| 1 | +import { render, fireEvent } from "@testing-library/react"; |
2 | 2 | import DxcQuickNav from "./QuickNav"; |
3 | 3 |
|
4 | 4 | const links = [ |
@@ -29,4 +29,52 @@ describe("QuickNav component tests", () => { |
29 | 29 | expect(getByText("Spacing")).toBeTruthy(); |
30 | 30 | expect(getByText("Button")).toBeTruthy(); |
31 | 31 | }); |
| 32 | + |
| 33 | + test("should call scrollIntoView when clicking on a link in hash router mode", () => { |
| 34 | + // Mock window.location.href to simulate hash router |
| 35 | + Object.defineProperty(window, "location", { |
| 36 | + value: { |
| 37 | + href: "http://localhost:3000/#/components", |
| 38 | + }, |
| 39 | + writable: true, |
| 40 | + }); |
| 41 | + |
| 42 | + // Mock document.getElementById and scrollIntoView |
| 43 | + const mockScrollIntoView = jest.fn(); |
| 44 | + const mockElement = { scrollIntoView: mockScrollIntoView }; |
| 45 | + const mockGetElementById = jest.fn().mockReturnValue(mockElement); |
| 46 | + document.getElementById = mockGetElementById; |
| 47 | + |
| 48 | + const { getByText } = render(<DxcQuickNav links={links} />); |
| 49 | + const overviewLink = getByText("Overview"); |
| 50 | + |
| 51 | + fireEvent.click(overviewLink); |
| 52 | + |
| 53 | + expect(mockGetElementById).toHaveBeenCalledWith("overview"); |
| 54 | + expect(mockScrollIntoView).toHaveBeenCalled(); |
| 55 | + }); |
| 56 | + |
| 57 | + test("should call scrollIntoView when clicking on a sublink in hash router mode", () => { |
| 58 | + // Mock window.location.href to simulate hash router |
| 59 | + Object.defineProperty(window, "location", { |
| 60 | + value: { |
| 61 | + href: "http://localhost:3000/#/components", |
| 62 | + }, |
| 63 | + writable: true, |
| 64 | + }); |
| 65 | + |
| 66 | + // Mock document.getElementById and scrollIntoView |
| 67 | + const mockScrollIntoView = jest.fn(); |
| 68 | + const mockElement = { scrollIntoView: mockScrollIntoView }; |
| 69 | + const mockGetElementById = jest.fn().mockReturnValue(mockElement); |
| 70 | + document.getElementById = mockGetElementById; |
| 71 | + |
| 72 | + const { getByText } = render(<DxcQuickNav links={links} />); |
| 73 | + const colorLink = getByText("Color"); |
| 74 | + |
| 75 | + fireEvent.click(colorLink); |
| 76 | + |
| 77 | + expect(mockGetElementById).toHaveBeenCalledWith("principles-color"); |
| 78 | + expect(mockScrollIntoView).toHaveBeenCalled(); |
| 79 | + }); |
32 | 80 | }); |
0 commit comments