|
| 1 | +import { signal } from "@preact/signals"; |
| 2 | +import { For, Show, useSignalRef } from "@preact/signals/utils"; |
| 3 | +import { render, createElement } from "preact"; |
| 4 | +import { act } from "preact/test-utils"; |
| 5 | + |
| 6 | +describe("@preact/signals-utils", () => { |
| 7 | + let scratch: HTMLDivElement; |
| 8 | + |
| 9 | + beforeEach(async () => { |
| 10 | + scratch = document.createElement("div"); |
| 11 | + document.body.appendChild(scratch); |
| 12 | + }); |
| 13 | + |
| 14 | + afterEach(async () => { |
| 15 | + render(null, scratch); |
| 16 | + }); |
| 17 | + |
| 18 | + describe("<Show />", () => { |
| 19 | + it("Should reactively show an element", () => { |
| 20 | + const toggle = signal(false)!; |
| 21 | + const Paragraph = (props: any) => <p>{props.children}</p>; |
| 22 | + act(() => { |
| 23 | + render( |
| 24 | + <Show when={toggle} fallback={<Paragraph>Hiding</Paragraph>}> |
| 25 | + <Paragraph>Showing</Paragraph> |
| 26 | + </Show>, |
| 27 | + scratch |
| 28 | + ); |
| 29 | + }); |
| 30 | + expect(scratch.innerHTML).to.eq("<p>Hiding</p>"); |
| 31 | + |
| 32 | + act(() => { |
| 33 | + toggle.value = true; |
| 34 | + }); |
| 35 | + expect(scratch.innerHTML).to.eq("<p>Showing</p>"); |
| 36 | + }); |
| 37 | + }); |
| 38 | + |
| 39 | + describe("<For />", () => { |
| 40 | + it("Should iterate over a list of signals", () => { |
| 41 | + const list = signal<Array<string>>([])!; |
| 42 | + const Paragraph = (p: any) => <p>{p.children}</p>; |
| 43 | + act(() => { |
| 44 | + render( |
| 45 | + <For each={list} fallback={<Paragraph>No items</Paragraph>}> |
| 46 | + {item => <Paragraph key={item}>{item}</Paragraph>} |
| 47 | + </For>, |
| 48 | + scratch |
| 49 | + ); |
| 50 | + }); |
| 51 | + expect(scratch.innerHTML).to.eq("<p>No items</p>"); |
| 52 | + |
| 53 | + act(() => { |
| 54 | + list.value = ["foo", "bar"]; |
| 55 | + }); |
| 56 | + expect(scratch.innerHTML).to.eq("<p>foo</p><p>bar</p>"); |
| 57 | + }); |
| 58 | + }); |
| 59 | + |
| 60 | + describe("useSignalRef", () => { |
| 61 | + it("should work", () => { |
| 62 | + let ref; |
| 63 | + const Paragraph = (p: any) => { |
| 64 | + ref = useSignalRef(null); |
| 65 | + return p.type === "span" ? ( |
| 66 | + <span ref={ref}>{p.children}</span> |
| 67 | + ) : ( |
| 68 | + <p ref={ref}>{p.children}</p> |
| 69 | + ); |
| 70 | + }; |
| 71 | + act(() => { |
| 72 | + render(<Paragraph type="p">1</Paragraph>, scratch); |
| 73 | + }); |
| 74 | + expect(scratch.innerHTML).to.eq("<p>1</p>"); |
| 75 | + expect((ref as any).value instanceof HTMLParagraphElement).to.eq(true); |
| 76 | + |
| 77 | + act(() => { |
| 78 | + render(<Paragraph type="span">1</Paragraph>, scratch); |
| 79 | + }); |
| 80 | + expect(scratch.innerHTML).to.eq("<span>1</span>"); |
| 81 | + expect((ref as any).value instanceof HTMLSpanElement).to.eq(true); |
| 82 | + }); |
| 83 | + }); |
| 84 | +}); |
0 commit comments