Skip to content

porada/vitest-react-serializer

Repository files navigation

vitest-react-serializer

Serialize React components into formatted HTML. Built for human-readable, reviewable component snapshot testing with Vitest.

Example

import { expect, test } from 'vitest';
import { FolderIcon } from './icons/index.ts';

test('renders without issues', () => {
    expect(
        <FolderIcon weight="fill" size={48} className="foo" />
    ).toMatchSnapshot();
});

By default, Vitest snapshots components as abstract element trees:

exports[`renders without issues 1`] = `
<FolderIcon
  className="foo"
  size={48}
  weight="fill"
/>
`;

Instead, vitest-react-serializer snapshots the rendered HTML, making component output changes easier to catch and review.

exports[`renders without issues 1`] = `
<svg
  xmlns="http://www.w3.org/2000/svg"
  width="48"
  height="48"
  fill="currentColor"
  viewBox="0 0 256 256"
  class="foo"
>
  <path
    d="M232,88V200.89A15.13,15.13,0,0,1,216.89,216H40a16,16,0,0,1-16-16V64A16,16,0,0,1,40,48H93.33a16.12,16.12,0,0,1,9.6,3.2L130.67,72H216A16,16,0,0,1,232,88Z"
  ></path>
</svg>
`;

Install

npm install --save-dev vitest-react-serializer
pnpm add --save-dev vitest-react-serializer

Usage

Reference vitest-react-serializer in your vitest.config.ts:

import { defineConfig } from 'vitest/config';

export default defineConfig({
    test: {
        snapshotSerializers: ['vitest-react-serializer'],
    },
});

Alternatively, scope the serializer to a test file (or even a single test) using expect.addSnapshotSerializer.

import { beforeAll, expect } from 'vitest';
import reactSerializer from 'vitest-react-serializer';

beforeAll(() => {
    expect.addSnapshotSerializer(reactSerializer);
});

Related

License

MIT © Dom Porada

About

Serialize React components into formatted HTML

Topics

Resources

License

Security policy

Stars

Watchers

Forks

Contributors