Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Testing and Performance

Testing Solid Components and Reactive Code

Test SolidJS code with Vitest and Solid Testing Library, test signals and effects inside createRoot, test async components and learn the pitfalls that fail tests.

Solid components are plain functions that run once, and reactive code is plain JavaScript that tracks what it reads. That makes tests pleasantly direct: create the state, change a signal, check the result. There are two layers to test: reactive logic (signals, memos, stores, custom primitives) and components (what the user sees and can do).

A test runner such as Vitest needs Node.js, a bundler plugin and a DOM implementation, none of which exist in this site's live editors. The project configuration and Testing Library tests are therefore read-only. The live examples use a tiny hand-written test/expect stand-in that runs the same reactive code in the browser, so you can see the techniques work.

Setting up Vitest

Solid's JSX needs the Solid compiler, which the Vite plugin provides, and tests need a DOM. A typical vitest.config.ts:

TypeScript
import { defineConfig } from "vitest/config";
import solid from "vite-plugin-solid";

export default defineConfig({
  plugins: [solid()],
  test: {
    environment: "jsdom",
    globals: true,
    setupFiles: ["./test/setup.ts"],      // e.g. import "@testing-library/jest-dom/vitest"
    server: { deps: { inline: [/solid-js/] } },
  },
  resolve: { conditions: ["development", "browser"] },
});

The browser condition matters: by default Node loads Solid's server build, in which signals do not update the way they do in the browser, and tests would fail in confusing ways. Starter templates created with npm create solid already include this setup.

Testing reactive logic with createRoot

Effects and memos need an owner (a reactive scope) or Solid warns that they will never be cleaned up. In a test, create one with createRoot, and dispose it when finished:

TypeScript
import { createRoot, createSignal, createMemo } from "solid-js";
import { test, expect } from "vitest";

test("memo follows its signal", () => {
  createRoot((dispose) => {
    const [n, setN] = createSignal(2);
    const doubled = createMemo(() => n() * 2);

    expect(doubled()).toBe(4);
    setN(5);
    expect(doubled()).toBe(10);

    dispose();
  });
});

Memos update synchronously, so you can assert right after setting. Effects are different: inside createRoot the first run of an effect happens only after the root function returns, so tests create the root, keep the setters and dispose, then write to the signals and check what the effect collected:

Stand-in test runner: signals, memos and effects

The runner is only 12 lines, which shows how little a framework needs from a test: a function that throws on failure. Real runners add watch mode, reports and mocking.

Testing custom primitives

A reusable primitive such as createCounter is just a function that creates signals. Test it inside createRoot, or use renderHook from the Solid Testing Library, which wraps the call in a root for you:

TypeScript
import { renderHook } from "@solidjs/testing-library";

test("createCounter increments", () => {
  const { result } = renderHook(() => createCounter(10));
  result.increment();
  expect(result.count()).toBe(11);
});

For effects that must be awaited, the library offers testEffect, which returns a promise settled when you call done inside the effect:

TypeScript
import { testEffect } from "@solidjs/testing-library";

test("effect sees the new value", () =>
  testEffect((done) => {
    const [v, setV] = createSignal(0);
    createEffect((run: number = 0) => {
      if (run === 0) { setV(1); }
      else { expect(v()).toBe(1); done(); }
      return run + 1;
    });
  }));

Testing components

@solidjs/testing-library renders a component into a real (jsdom) DOM and offers the Testing Library queries. The philosophy is to test what the user can see and do, not implementation details such as which signal exists.

TSX
import { render, screen } from "@solidjs/testing-library";
import userEvent from "@testing-library/user-event";
import { Counter } from "./Counter";

test("increments when clicked", async () => {
  const user = userEvent.setup();
  render(() => <Counter initial={3} />);        // note: a function, not <Counter/> directly

  expect(screen.getByText("Count: 3")).toBeInTheDocument();
  await user.click(screen.getByRole("button", { name: /increment/i }));
  expect(screen.getByText("Count: 4")).toBeInTheDocument();
});

Two Solid-specific habits:

  1. render takes a function (() => <Counter />), so the component is created inside the library's reactive root.
  2. No re-render: after a click the DOM updates in place, so you query again with getByText; you never "wait for the component to re-run" because it does not.

Prefer role and label queries (getByRole, getByLabelText) over test ids: they check accessibility at the same time.

Async components

Components that wait for a resource show a fallback first. Use the async findBy queries, which retry until the element appears or a timeout expires:

TSX
render(() => (
  <Suspense fallback={<p>Loading...</p>}>
    <UserCard id={1} />
  </Suspense>
));

expect(screen.getByText("Loading...")).toBeInTheDocument();
expect(await screen.findByText("Ada Lovelace")).toBeInTheDocument();

Mock the network with your tool of choice (Mock Service Worker, or vi.stubGlobal("fetch", ...)) so tests are fast and deterministic.

Testing the DOM output without a library

For small pieces, you can skip the library: render into a detached element and read it. This second stand-in shows the idea, with the render call and the DOM assertions that a Testing Library test performs.

Stand-in: render a component and assert on the DOM

The third check is worth noting: the button is the same DOM node after updates, which is Solid's fine-grained model made visible.

Common mistakes

  • Missing browser condition: signals behave as on the server; effects never re-run. Set resolve.conditions.
  • Destructuring props in the component under test: it passes in the browser for the first render and fails when props change. Tests that change a prop catch this.
  • Effects outside a root: warnings about computations created outside createRoot. Wrap them or use renderHook.
  • Forgetting cleanup: Solid Testing Library cleans up automatically after each test when globals are on; hand-made roots need dispose().
  • Asserting too early: use findBy... for anything that waits for a resource.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why configure resolve.conditions with browser for Vitest?

    Solid publishes separate server and browser builds, and tests need the browser one.
  2. 2. Why wrap reactive logic in createRoot in a test?

    Without an owner Solid cannot clean up computations and warns about leaks.
  3. 3. What does render(() => <Counter />) take as its argument?

    A function lets the library create the component inside its own reactive root.
  4. 4. Which query waits for an element that appears after a resource loads?

    findBy queries return a promise that retries until the element exists or time runs out.

Summary

  • Test reactive logic inside createRoot (or renderHook) and dispose when done; memos update synchronously.
  • Set the browser condition and the Solid Vite plugin in Vitest, and use jsdom.
  • Render with @solidjs/testing-library: render(() => <C />), query by role, use findBy for async.
  • There is no re-render to wait for; the same DOM nodes are updated in place.
  • Mock the network, clean up roots, and test behavior rather than internals.

Next: Performance: Fine-Grained Updates in Practice