).pipe(
Atom.serializable({
key: "ssr-wire",
schema: AsyncResult.Schema({ success: Schema.Number })
})
)
// Server: dehydrate
const serverRegistry = AtomRegistry.make()
serverRegistry.mount(atom)
;(serverRegistry.getNodes().get("ssr-wire") as any).setValue(
AsyncResult.success(42)
)
const dehydratedState = Hydration.dehydrate(serverRegistry)
// Simulate wire transfer (seroval / JSON)
const wireTransferred = JSON.parse(JSON.stringify(dehydratedState))
// Client: hydrate from wire-transferred state
function TestComponent() {
const value = useAtomValue(atom)
return (
{AsyncResult.isSuccess(value) ? value.value : "not-success"}
)
}
render(
)
expect(screen.getByTestId("ssr-wire-value")).toHaveTextContent("42")
})
test("empty state is a no-op", () => {
function TestComponent() {
return OK
}
render(
)
expect(screen.getByTestId("hydration-empty-state")).toHaveTextContent("OK")
})
test("hydrate with no state is a no-op", () => {
function TestComponent() {
return OK
}
render(
)
expect(screen.getByTestId("hydration-no-state")).toHaveTextContent("OK")
})
})
describe("SSR", () => {
it("should run atom's during SSR by default", () => {
const getCount = vi.fn(() => 0)
const counterAtom = Atom.make(getCount)
function TestComponent() {
const count = useAtomValue(counterAtom)
return {count}
}
function App() {
return
}
const ssrHtml = renderToString()
expect(getCount).toHaveBeenCalled()
expect(ssrHtml).toContain("0")
render()
expect(getCount).toHaveBeenCalled()
expect(screen.getByText("0")).toBeInTheDocument()
})
})
it("should not execute Atom effects during SSR when using withServerSnapshot", () => {
const mockFetchData = vi.fn(() => 0)
const userDataAtom = Atom.make(Effect.sync(() => mockFetchData())).pipe(
Atom.withServerValueInitial
)
function TestComponent() {
const result = useAtomValue(userDataAtom)
return {result._tag}
}
function App() {
return
}
const ssrHtml = renderToString()
expect(mockFetchData).not.toHaveBeenCalled()
expect(ssrHtml).toContain("Initial")
render()
expect(mockFetchData).toHaveBeenCalled()
expect(screen.getByText("Success")).toBeInTheDocument()
})
})