I’ve been using Preact as my alternative (API compatible) React of choice for a few side projects for a while now, the main advantage being the API compatibility with a significantly smaller sized addition to dependencies.

Likewise, my favorite CSS-in-JS microlibrary: Picostyle has similar file-size advantages.

Micro-libraries are great because they are small enough to be able to dig into their source code quickly and make customizations.

Snapshot testing with Preact and Picostyle

It’s not immediately obvious how to test Preact JSX within a Jest snapshot test, especially when they are styled with Picostyle. However, the great thing about micro-libraries is the minimal length of their source code. We can dig into them to see what missing links they might need in order to do what we want to do:

  • Preact needs a render to string wrapper for snapshots: preact-render-to-string works fine

  • Picostyle appends a stylesheet to the virtual DOM (VDOM) while generating CSS class names: to get the CSS rules we just need to read them back out from the VDOM. This can only be done in sequence (after the render()).

expect(render(renderable)).toMatchSnapshot();
expect(getCSSRules()).toMatchSnapshot('css');

A Jest helper lives inside the setup file for the CSS rules: getCSSRules()

See src/client/components/AdminScreen/TableRow.spec.tsx for a full example.