|
| 1 | +import type { FC } from "react"; |
| 2 | +import { describe, it, expect, beforeEach, afterEach } from "vitest"; |
| 3 | +import { render, screen } from "@testing-library/react"; |
| 4 | +import { registry } from "@/component/Registry"; |
| 5 | +import { type ComponentProps } from "./Component"; |
| 6 | +import { Children } from "./Children"; |
| 7 | + |
| 8 | +describe("Children", () => { |
| 9 | + beforeEach(() => { |
| 10 | + registry.clear(); |
| 11 | + }); |
| 12 | + |
| 13 | + afterEach(() => { |
| 14 | + registry.clear(); |
| 15 | + }); |
| 16 | + |
| 17 | + function expectDocumentIsEmpty() { |
| 18 | + // Note, the following 3 lines test that document is empty |
| 19 | + // but there is always one empty "div" in it. |
| 20 | + expect(document.body.firstElementChild).not.toBe(null); |
| 21 | + expect(document.body.firstElementChild!.tagName).toBe("DIV"); |
| 22 | + expect(document.body.firstElementChild!.firstElementChild).toBe(null); |
| 23 | + } |
| 24 | + |
| 25 | + it("should not render undefined nodes", () => { |
| 26 | + render(<Children onChange={() => {}} />); |
| 27 | + expectDocumentIsEmpty(); |
| 28 | + }); |
| 29 | + |
| 30 | + it("should not render empty nodes", () => { |
| 31 | + render(<Children nodes={[]} onChange={() => {}} />); |
| 32 | + expectDocumentIsEmpty(); |
| 33 | + }); |
| 34 | + |
| 35 | + it("should render all child types", () => { |
| 36 | + interface DivProps extends ComponentProps { |
| 37 | + text: string; |
| 38 | + } |
| 39 | + const Div: FC<DivProps> = ({ text }) => <div>{text}</div>; |
| 40 | + registry.register("Div", Div as FC<ComponentProps>); |
| 41 | + const divProps = { |
| 42 | + type: "Div", |
| 43 | + text: "Hello", |
| 44 | + onChange: () => {}, |
| 45 | + }; |
| 46 | + render( |
| 47 | + <Children |
| 48 | + nodes={[ |
| 49 | + divProps, // ok, regular component |
| 50 | + "World", // ok, text |
| 51 | + null, // ok, not rendered |
| 52 | + undefined, // ok, not rendered |
| 53 | + <div />, // not ok, emits warning, not rendered |
| 54 | + ]} |
| 55 | + onChange={() => {}} |
| 56 | + />, |
| 57 | + ); |
| 58 | + // to inspect rendered component, do: |
| 59 | + // expect(document.body).toEqual({}); |
| 60 | + expect(screen.getByText("Hello")).not.toBeUndefined(); |
| 61 | + expect(screen.getByText("World")).not.toBeUndefined(); |
| 62 | + }); |
| 63 | +}); |
0 commit comments