|
| 1 | +import React from "react"; |
| 2 | +import { render, cleanup } from "@testing-library/react"; |
| 3 | +import ListNestingStyles from "./ListNestingStyles"; |
| 4 | + |
| 5 | +// Mock getListNestingStyles |
| 6 | +jest.mock("draftjs-conductor", () => ({ |
| 7 | + getListNestingStyles: (max: number) => `.depth-${max} { color: red; }`, |
| 8 | +})); |
| 9 | + |
| 10 | +describe("ListNestingStyles", () => { |
| 11 | + let originalAdoptedStyleSheets: CSSStyleSheet[]; |
| 12 | + let mockSheet: CSSStyleSheet; |
| 13 | + |
| 14 | + beforeEach(() => { |
| 15 | + // Save original adoptedStyleSheets |
| 16 | + originalAdoptedStyleSheets = [...document.adoptedStyleSheets]; |
| 17 | + // Mock adoptedStyleSheets as a mutable array |
| 18 | + Object.defineProperty(document, "adoptedStyleSheets", { |
| 19 | + configurable: true, |
| 20 | + // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 21 | + // @ts-ignore |
| 22 | + get: () => global.adoptedStyleSheets || [], |
| 23 | + set: (sheets) => { |
| 24 | + // eslint-disable-next-line @typescript-eslint/ban-ts-comment |
| 25 | + // @ts-ignore |
| 26 | + global.adoptedStyleSheets = sheets; |
| 27 | + }, |
| 28 | + }); |
| 29 | + document.adoptedStyleSheets = []; |
| 30 | + // Mock CSSStyleSheet |
| 31 | + mockSheet = { |
| 32 | + replaceSync: jest.fn(), |
| 33 | + } as unknown as CSSStyleSheet; |
| 34 | + window.CSSStyleSheet = jest.fn(() => mockSheet); |
| 35 | + }); |
| 36 | + |
| 37 | + afterEach(() => { |
| 38 | + // Restore adoptedStyleSheets |
| 39 | + Object.defineProperty(document, "adoptedStyleSheets", { |
| 40 | + configurable: true, |
| 41 | + value: originalAdoptedStyleSheets, |
| 42 | + writable: true, |
| 43 | + }); |
| 44 | + cleanup(); |
| 45 | + }); |
| 46 | + |
| 47 | + it("injects a stylesheet when mounted with max", () => { |
| 48 | + render(<ListNestingStyles max={3} />); |
| 49 | + expect(window.CSSStyleSheet).toHaveBeenCalled(); |
| 50 | + expect(mockSheet.replaceSync).toHaveBeenCalledWith( |
| 51 | + ".depth-3 { color: red; }", |
| 52 | + ); |
| 53 | + expect(document.adoptedStyleSheets).toContain(mockSheet); |
| 54 | + }); |
| 55 | + |
| 56 | + it("removes the stylesheet on unmount", () => { |
| 57 | + const { unmount } = render(<ListNestingStyles max={2} />); |
| 58 | + expect(document.adoptedStyleSheets).toContain(mockSheet); |
| 59 | + unmount(); |
| 60 | + expect(document.adoptedStyleSheets).not.toContain(mockSheet); |
| 61 | + }); |
| 62 | + |
| 63 | + it("does nothing if max is not provided", () => { |
| 64 | + render(<ListNestingStyles />); |
| 65 | + expect(window.CSSStyleSheet).not.toHaveBeenCalled(); |
| 66 | + expect(document.adoptedStyleSheets).toHaveLength(0); |
| 67 | + }); |
| 68 | +}); |
0 commit comments