|
| 1 | +import { render, type RenderResult } from "@testing-library/react"; |
| 2 | +import type { JSX } from "react"; |
| 3 | +import { errorHandler, errorMsg, type ErrorMessage } from "../ErrorHandling"; |
| 4 | +import type { InitResult, UpdateMap } from "../Types"; |
| 5 | +import { useElmish } from "../useElmish"; |
| 6 | +import { getCreateUpdateArgs } from "./getCreateUpdateArgs"; |
| 7 | +import { getUpdateFn } from "./getUpdateFn"; |
| 8 | +import { renderWithModel } from "./renderWithModel"; |
| 9 | + |
| 10 | +interface Model { |
| 11 | + value1: string; |
| 12 | + value2: string; |
| 13 | + subPage: string; |
| 14 | +} |
| 15 | + |
| 16 | +interface Props {} |
| 17 | + |
| 18 | +type Message = { name: "doubleDefer" } | ErrorMessage; |
| 19 | + |
| 20 | +const Msg = { |
| 21 | + doubleDefer: (): Message => ({ name: "doubleDefer" }), |
| 22 | + ...errorMsg, |
| 23 | +}; |
| 24 | + |
| 25 | +function init(): InitResult<Model, Message> { |
| 26 | + return [ |
| 27 | + { |
| 28 | + value1: "", |
| 29 | + value2: "", |
| 30 | + subPage: "", |
| 31 | + }, |
| 32 | + ]; |
| 33 | +} |
| 34 | + |
| 35 | +const update: UpdateMap<Props, Model, Message> = { |
| 36 | + doubleDefer(_msg, _model, _props, { defer }) { |
| 37 | + defer({ value2: "deferred" }); |
| 38 | + defer({ subPage: "subPage" }); |
| 39 | + |
| 40 | + return [{ value1: "computed" }]; |
| 41 | + }, |
| 42 | + |
| 43 | + ...errorHandler(), |
| 44 | +}; |
| 45 | + |
| 46 | +function Playground(props: Props): JSX.Element { |
| 47 | + const [, dispatch] = useElmish({ name: "Playground", init, update, props }); |
| 48 | + |
| 49 | + return ( |
| 50 | + <div> |
| 51 | + <button type={"button"} onClick={() => dispatch(Msg.doubleDefer())}> |
| 52 | + {"Compute"} |
| 53 | + </button> |
| 54 | + </div> |
| 55 | + ); |
| 56 | +} |
| 57 | + |
| 58 | +function renderPlayground(modelTemplate?: Partial<Model>): RenderResult { |
| 59 | + const model = { |
| 60 | + ...init()[0], |
| 61 | + ...modelTemplate, |
| 62 | + }; |
| 63 | + |
| 64 | + return renderWithModel(() => render(<Playground />), model); |
| 65 | +} |
| 66 | + |
| 67 | +const getUpdateArgs = getCreateUpdateArgs(init, () => ({})); |
| 68 | +const updateFn = getUpdateFn(update); |
| 69 | + |
| 70 | +describe("Playground", () => { |
| 71 | + it("renders without crashing", () => { |
| 72 | + const { container } = renderPlayground(); |
| 73 | + |
| 74 | + expect(container).toBeTruthy(); |
| 75 | + }); |
| 76 | + |
| 77 | + describe("doubleDefer", () => { |
| 78 | + it("computes the values", async () => { |
| 79 | + const args = getUpdateArgs(Msg.doubleDefer()); |
| 80 | + |
| 81 | + const [model] = updateFn(...args); |
| 82 | + |
| 83 | + expect(model).toStrictEqual({ value1: "computed", value2: "deferred", subPage: "subPage" }); |
| 84 | + }); |
| 85 | + }); |
| 86 | +}); |
0 commit comments