|
| 1 | +import { For, Show } from "../../src"; |
| 2 | +import { |
| 3 | + act, |
| 4 | + checkHangingAct, |
| 5 | + createRoot, |
| 6 | + Root, |
| 7 | +} from "../../../test/shared/utils"; |
| 8 | +import { signal } from "@preact/signals-react"; |
| 9 | +import { createElement } from "react"; |
| 10 | + |
| 11 | +describe("@preact/signals-react-utils", () => { |
| 12 | + let scratch: HTMLDivElement; |
| 13 | + let root: Root; |
| 14 | + async function render(element: Parameters<Root["render"]>[0]) { |
| 15 | + await act(() => root.render(element)); |
| 16 | + } |
| 17 | + |
| 18 | + beforeEach(async () => { |
| 19 | + scratch = document.createElement("div"); |
| 20 | + document.body.appendChild(scratch); |
| 21 | + root = await createRoot(scratch); |
| 22 | + }); |
| 23 | + |
| 24 | + afterEach(async () => { |
| 25 | + checkHangingAct(); |
| 26 | + await act(() => root.unmount()); |
| 27 | + scratch.remove(); |
| 28 | + }); |
| 29 | + |
| 30 | + describe("<Show />", () => { |
| 31 | + it("Should reactively show an element", () => { |
| 32 | + const toggle = signal(false)!; |
| 33 | + const Paragraph = (p: any) => <p>{p.children}</p>; |
| 34 | + act(() => { |
| 35 | + render( |
| 36 | + <Show when={toggle} fallback={<Paragraph>Hiding</Paragraph>}> |
| 37 | + <Paragraph>Showing</Paragraph> |
| 38 | + </Show> |
| 39 | + ); |
| 40 | + }); |
| 41 | + expect(scratch.innerHTML).to.eq("<p>Hiding</p>"); |
| 42 | + |
| 43 | + act(() => { |
| 44 | + toggle.value = true; |
| 45 | + }); |
| 46 | + expect(scratch.innerHTML).to.eq("<p>Showing</p>"); |
| 47 | + }); |
| 48 | + }); |
| 49 | + |
| 50 | + describe("<For />", () => { |
| 51 | + it("Should iterate over a list of signals", () => { |
| 52 | + const list = signal<Array<string>>([])!; |
| 53 | + const Paragraph = (p: any) => <p>{p.children}</p>; |
| 54 | + act(() => { |
| 55 | + render( |
| 56 | + <For each={list} fallback={<Paragraph>No items</Paragraph>}> |
| 57 | + {item => <Paragraph key={item}>{item}</Paragraph>} |
| 58 | + </For> |
| 59 | + ); |
| 60 | + }); |
| 61 | + expect(scratch.innerHTML).to.eq("<p>No items</p>"); |
| 62 | + |
| 63 | + act(() => { |
| 64 | + list.value = ["foo", "bar"]; |
| 65 | + }); |
| 66 | + expect(scratch.innerHTML).to.eq("<p>foo</p><p>bar</p>"); |
| 67 | + }); |
| 68 | + }); |
| 69 | +}); |
0 commit comments