You change one line in the +1 button, and now it adds 2. The page still shows, there's no error, and it may be a long while before anyone notices. A test catches a mistake like that first.
A test is code that checks your code automatically: it mounts a component, presses its buttons like a user, then compares what shows. For Solid, the tools are Vitest (which runs the tests) and @solidjs/testing-library (which mounts components and finds things in them the way a user would). If you come from React, the second one is Solid's version of React Testing Library, so you search the same way. It's like the till check at Nadia's Bookshop every morning before opening: the clerk scans one sample book, then sees whether the screen shows the right number. If it's wrong, it is caught before the first buyer arrives.
Setup
npm install -D vitest jsdom @solidjs/testing-library @testing-library/user-event @testing-library/jest-dom
// vitest.config.js
import { defineConfig } from "vitest/config"
import solid from "vite-plugin-solid"
export default defineConfig({
plugins: [solid()],
test: { environment: "jsdom", globals: true },
})
@solidjs/testing-libraryis Solid's official testing library, Solid's version of React Testing Library. It used to be calledsolid-testing-library.vite-plugin-solidis already in a Vite Solid project. It transforms the JSX in test files, just as in the app.environment: "jsdom"gives the tests a fakedocumentin Node, so components can be mounted without a browser.globals: trueis covered in the cleanup section.
The component under test
This is the exercise:
// src/Counter.jsx
import { createSignal } from "solid-js"
export default function Counter() {
const [count, setCount] = createSignal(0)
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount((c) => c + 1)}>+1</button>
</div>
)
}
A component that is easy to test shows its state on screen: the <p> says Count: 0, one click on +1 makes it Count: 1, two make it Count: 2.
A first test: render, screen, fireEvent
// src/Counter.test.jsx
import { describe, it, expect } from "vitest"
import { render, screen, fireEvent } from "@solidjs/testing-library"
import userEvent from "@testing-library/user-event"
import "@testing-library/jest-dom/vitest"
import Counter from "./Counter"
describe("Counter", () => {
it("starts at Count: 0", () => {
render(() => <Counter />)
expect(screen.getByText("Count: 0")).toBeInTheDocument()
})
it("+1 once makes Count: 1", () => {
render(() => <Counter />)
fireEvent.click(screen.getByRole("button", { name: "+1" }))
expect(screen.getByText("Count: 1")).toBeInTheDocument()
})
it("+1 twice makes Count: 2", async () => {
const user = userEvent.setup()
render(() => <Counter />)
await user.click(screen.getByRole("button", { name: "+1" }))
await user.click(screen.getByRole("button", { name: "+1" }))
expect(screen.getByText("Count: 2")).toBeInTheDocument()
})
})
npx vitest run, captured from a real project (Vitest 5, @solidjs/testing-library 0.8):
RUN v5.0.3 /home/nadia/bookshop
Test Files 1 passed (1)
Tests 3 passed (3)
Start at 19:30:15
Duration 1.06s (environment 66%, transform 10%, tests 10%, setup 10%, import 4%, worker 1%)
render(() => <Counter />)mounts the component in a new<div>indocument.body. Its argument is a function, sorenderitself runsCounterinside its root, and the reactive scope (the owner) is set up correctly: effects can be taken down and a Provider's context gets through. Tested withrender(<Counter />)without a function: the console printscomputations created outside a `createRoot` or `render` will never be disposed, then the test stops withTypeError: code is not a function(withwrapper:TypeError: Comp is not a function), and nothing is shown.screen.getByText("Count: 0")finds the element whose text is exactly that.screen.getByRole("button", { name: "+1" })searches the way a screen reader does: its role is button, its name is+1.fireEvent.click(...)sends one click event. Solid updates the DOM right then, so the next line can check straight away.userEventimitates a user more fully (pointer, focus, then click), and is called withawait.toBeInTheDocument()comes from@testing-library/jest-dom/vitest.
When a test fails
Change the button to setCount((c) => c + 2). An excerpt of the real output:
FAIL src/Counter.test.jsx > Counter > +1 once makes Count: 1
TestingLibraryElementError: Unable to find an element with the text: Count: 1. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
Ignored nodes: comments, script, style
<body>
<div>
<div>
<p>
Count:
2
</p>
The test shows the page as it was when it failed: Count: 2, not Count: 1. A typical Solid bug is caught too: const value = count() in the component body and then <p>Count: {value}</p> fails the same two tests, with Count: and 0 in the dump, because the number is read once.
Cleanup: every test starts from a clean page
Remove globals: true from vitest.config.js and leave only environment: "jsdom". The second test then fails. The real output:
FAIL src/Counter.test.jsx > Counter > +1 once makes Count: 1
TestingLibraryElementError: Found multiple elements with the role "button" and name "+1"
@solidjs/testing-library takes the component down after each test through Vitest's afterEach, but afterEach only exists with globals: true. Without it, the first test's Counter is still in document.body, and getByRole finds two buttons. Pick one: globals: true, or afterEach(cleanup) with cleanup from @solidjs/testing-library.
Testing a primitive inside createRoot
The primitive from the Custom Primitives lesson is tested without a view. Effects and memos need an owner, so wrap it in createRoot:
import { it, expect } from "vitest"
import { createRoot } from "solid-js"
import { createCounter } from "./createCounter"
it("increment, decrement, reset", () => {
createRoot((dispose) => {
const counter = createCounter(10)
counter.increment()
expect(counter.count()).toBe(11)
counter.decrement()
counter.decrement()
expect(counter.count()).toBe(9)
counter.reset()
expect(counter.count()).toBe(10)
dispose()
})
})
dispose() at the end takes down everything the primitive made, timers and onCleanup included. @solidjs/testing-library also has renderHook for the same job.
⚠️ Why the test goes red
render(<Counter />)without a function. The component is made beforerendersets up its root: the warning above shows, then the test stops withTypeError: code is not a function.- Forgetting
globals: true(orafterEach(cleanup)). The previous test's component stays behind, sogetBy...finds more than one element. - A component that keeps its state hidden. Tests read the screen. The exercise checks the
<p>says exactlyCount: 0, thenCount: 1after one click andCount: 2after two, so the increase must continue from the old value:setCount((c) => c + 1).
TL;DR: Solid tests use Vitest with environment: "jsdom" and globals: true, plus @solidjs/testing-library. render(() => <Counter />) (always a function, so the reactive scope is set up correctly) mounts the component, screen.getByText and screen.getByRole("button", { name: "+1" }) find things the way a user does, fireEvent.click or await user.click presses them, and expect(...).toBeInTheDocument() checks the result. A failing test prints the page as it was. globals: true makes every test start from a clean page. A primitive is tested inside createRoot((dispose) => { ...; dispose() }).
⚡ A component that's easy to test
Write:
export default function Counter() {
const [count, setCount] = createSignal(0)
return (
<div>
<p>Count: {count()}</p>
<button onClick={() => setCount((c) => c + 1)}>+1</button>
</div>
)
}
Meaning: Tests read the screen, not the signal. So a component that's easy to test shows its state on screen: Count: 0, one click Count: 1, two clicks Count: 2.
⚡ render takes a function
Write:
render(() => <Counter />)
fireEvent.click(screen.getByRole("button", { name: "+1" }))
expect(screen.getByText("Count: 1")).toBeInTheDocument()
Meaning: The argument of render is a function, so render itself runs Counter inside its root, and the reactive scope is set up correctly. screen.getByRole searches the way a screen reader does: its role is button, its name is +1.
⚡ Every test starts from a clean page
Guess first: globals: true is removed from vitest.config.js. Does the second test still pass?
It fails, with Found multiple elements with the role "button". Without globals: true, there's no afterEach, so the first test's Counter is still in document.body.
Meaning: Pick one: globals: true, or afterEach(cleanup) with cleanup from @solidjs/testing-library.