@noma.to/qwik-testing-library
v1.7.1
Published
Simple and complete Qwik testing utilities that encourage good testing practices.
Readme
Table of Contents
The Problem
You want to write maintainable tests for your Qwik components.
This Solution
@noma.to/qwik-testing-library is a lightweight library for testing Qwik
components. It provides functions on top of qwik and
@testing-library/dom so you can mount Qwik components and query their
rendered output in the DOM. Its primary guiding principle is:
The more your tests resemble the way your software is used, the more confidence they can give you.
Installation
This module is distributed via npm which is bundled with node and
should be installed as one of your project's devDependencies:
npm install --save-dev @noma.to/qwik-testing-library @testing-library/domThis library supports Qwik v1 (@builder.io/qwik 1.12.0 and above), Qwik v2 (@qwik.dev/core 2.0.0-rc.0 and
above) and @testing-library/dom versions 10.1.0 and above.
You may also be interested in installing @testing-library/jest-dom and @testing-library/user-event so you can
use the custom jest matchers and the user event library to test interactions with the DOM.
npm install --save-dev @testing-library/jest-dom @testing-library/user-eventFinally, we need a DOM environment to run the tests in.
This library is tested with both jsdom and happy-dom:
npm install --save-dev jsdom
# or
npm install --save-dev happy-domWith jsdom, use version 30.1.1 or above.
Setup
We recommend using @noma.to/qwik-testing-library with Vitest as your test
runner.
If you haven't done so already, install vitest:
npm install --save-dev vitestAfter that, we need to configure Vitest so it can run your tests.
Add the test section to your vite.config.ts:
// vite.config.ts
test: {
environment: "jsdom", // or "happy-dom"
setupFiles: [
"@noma.to/qwik-testing-library/setup/qwik-v1", // or ".../setup/qwik-v2" with Qwik v2
"@testing-library/jest-dom/vitest", // optional, for DOM matchers
],
globals: true,
},Pick the setup module matching your Qwik version. It must run before any Qwik code loads, so keep it in
setupFiles. @noma.to/qwik-testing-library/setup still works and is the same as setup/qwik-v1.
By default, Qwik Testing Library cleans everything up automatically for you.
You can opt out of this by setting the environment variable QTL_SKIP_AUTO_CLEANUP to true.
Then in your tests, you can call the cleanup function when needed.
For example:
import {cleanup} from "@noma.to/qwik-testing-library";
import {afterEach} from "vitest";
afterEach(cleanup);Finally, edit your tsconfig.json to declare the following global types:
// tsconfig.json
{
"compilerOptions": {
"types": [
+ "vite/client",
+ "vitest/globals",
+ "@testing-library/jest-dom/vitest"
]
},
"include": ["src"]
}Qwik v2
Everything in this README works with Qwik v2: import Qwik APIs from @qwik.dev/core instead of @builder.io/qwik in
the examples. A few things behave differently than with Qwik v1.
Visible tasks finish after render resolves
With Qwik v2, waiting for visible tasks is not just recommended, it's required: a getBy*
query right after render doesn't see their changes yet.
This is tracked upstream in QwikDev/qwik#9121.
renderHook waits for the computed signals your hook returns
renderHook waits for the computed signals your hook returns, either as its result or as a top-level property or
array element, so you can read them right away:
function useCounter() {
const count = useSignal(1);
const doubled = useComputed$(() => count.value * 2);
return { count, doubled };
}
const { result } = await renderHook(useCounter);
expect(result.doubled.value).toBe(2);Computed signals update as soon as their dependencies change:
result.count.value = 5;
expect(result.doubled.value).toBe(10);For an async computed, or a computed nested deeper in the result, wait for it with promise() like you would in Qwik:
function useCounter() {
const count = useSignal(1);
const doubled = useComputed$(async () => count.value * 2);
return { count, doubled };
}
const { result } = await renderHook(useCounter);
result.count.value = 5;
await result.doubled.promise();
expect(result.doubled.value).toBe(10);Errors thrown by your components don't fail your tests
When a component throws while rendering, or one of its tasks or event handlers throws, Qwik v2 doesn't log the error and your test keeps running. Assert on what your component renders: a test expecting content that an error prevented from rendering still fails.
Examples
Below are some examples of how to use @noma.to/qwik-testing-library to tests your Qwik components.
You can also learn more about the queries and user events over at the Testing Library website.
Qwikstart
This is a minimal setup to get you started, with line-by-line explanations.
// counter.spec.tsx
// import qwik-testing methods
import {screen, render, waitFor} from "@noma.to/qwik-testing-library";
// import the userEvent methods to interact with the DOM
import {userEvent} from "@testing-library/user-event";
// import the component to be tested
import {Counter} from "./counter";
// describe the test suite
describe("<Counter />", () => {
// describe the test case
it("should increment the counter", async () => {
// setup user event
const user = userEvent.setup();
// render the component into the DOM
await render(<Counter/>);
// retrieve the 'increment count' button
const incrementBtn = screen.getByRole("button", {name: /increment count/});
// click the button twice
await user.click(incrementBtn);
await user.click(incrementBtn);
// assert that the counter is now 2
expect(await screen.findByText(/count:2/)).toBeInTheDocument();
});
})Waiting for Visible Tasks
A useVisibleTask$ runs once its component is visible, after it has rendered, just like in the browser.
Treat what it does as asynchronous: wait for it with findBy* queries or waitFor instead of asserting right after
render.
// clock.tsx
export const Clock = component$(() => {
const time = useSignal("--:--");
useVisibleTask$(() => {
time.value = "12:00";
});
return <p>{time.value}</p>;
});// clock.spec.tsx
await render(<Clock />);
expect(await screen.findByText("12:00")).toBeInTheDocument();The same goes for changes outside your component, such as a style set on document.body:
await render(<ScrollLock />);
await waitFor(() => expect(document.body).toHaveStyle({ overflow: "hidden" }));An event listener added by a visible task can't be waited for: an event fired before it exists is lost.
Listen to global events with useOnDocument or useOnWindow instead. They're ready as soon as render resolves:
// modal.tsx
export const Modal = component$(() => {
const open = useSignal(true);
useOnDocument(
"keydown",
$((event) => {
if (event.key === "Escape") open.value = false;
}),
);
return open.value && <div role="dialog">Hello</div>;
});// modal.spec.tsx
const user = userEvent.setup();
await render(<Modal />);
await user.keyboard("{Escape}");
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());Testing Hooks (experimental)
[!WARNING] This feature is under a testing phase and thus experimental. Its API may change in the future, so use it at your own risk.
renderHook lets you test custom hooks in isolation, without building a wrapper component by hand.
This is especially useful for library authors who need to battle-test the hooks they provide to their users.
// use-counter.tsx
import { $, useSignal } from "@builder.io/qwik";
export function useCounter(initial = 0) {
const count = useSignal(initial);
const increment$ = $(() => count.value++);
return { count, increment$ };
}// use-counter.spec.tsx
import { renderHook } from "@noma.to/qwik-testing-library";
import { useCounter } from "./use-counter";
describe("useCounter", () => {
it("should start at 0", async () => {
const { result } = await renderHook(useCounter);
expect(result.count.value).toBe(0);
});
it("should increment", async () => {
const { result } = await renderHook(useCounter);
await result.increment$();
expect(result.count.value).toBe(1);
});
});The result is the direct return value of your hook callback. Because Qwik signals are stable reactive
references, you can read and mutate them directly — no .current wrapper needed.
ESLint qwik/use-method-usage
With Qwik v2, the Qwik ESLint plugin allows use* calls inside renderHook callbacks, so you can pass arguments
inline:
const { result } = await renderHook(() => useCounter(10));With Qwik v1, the plugin only allows use* calls inside component$ or use*-named functions. When you need to pass
arguments to your hook, wrap it in a use*-named function to stay lint-clean:
// passing the hook by reference — lint-clean
const { result } = await renderHook(useCounter);
// passing arguments — extract a use*-named function
function useCounterFrom10() {
return useCounter(10);
}
const { result } = await renderHook(useCounterFrom10);Providing Context
If your hook depends on context, use the wrapper option to provide it:
import { renderHook } from "@noma.to/qwik-testing-library";
import { component$, createContextId, useContextProvider, useStore, Slot } from "@builder.io/qwik";
import { useTheme } from "./use-theme";
const ThemeContext = createContextId<{ mode: string }>("theme");
const ThemeProvider = component$(() => {
useContextProvider(ThemeContext, useStore({ mode: "dark" }));
return <Slot />;
});
it("should read theme from context", async () => {
const { result } = await renderHook(useTheme, {
wrapper: ThemeProvider,
});
expect(result.mode).toBe("dark");
});Cleanup
renderHook integrates with automatic cleanup, just like render.
You can also call unmount() manually if needed:
const { result, unmount } = await renderHook(useCounter);
// ... assertions ...
unmount();Mocking Component Callbacks (experimental)
[!WARNING] This feature is under a testing phase and thus experimental. Its API may change in the future, so use it at your own risk.
Setup
Optionally, you can install @noma.to/qwik-mock to mock callbacks of Qwik components. It provides a mock$ function
that can be used to create a mock of a QRL and verify interactions on your Qwik components.
npm install --save-dev @noma.to/qwik-mockIt is not a replacement of regular mocking functions (such as vi.fn and vi.mock) as its intended use is only for
testing callbacks of Qwik components.
Usage
Here's an example on how to use the mock$ function:
// import qwik-testing methods
import {render, screen, waitFor} from "@noma.to/qwik-testing-library";
// import qwik-mock methods
import {clearAllMocks, mock$} from "@noma.to/qwik-mock";
// import the userEvent methods to interact with the DOM
import {userEvent} from "@testing-library/user-event";
// import the component to be tested
import {Counter} from "./counter";
// describe the test suite
describe("<Counter />", () => {
// initialize a mock
const onChangeMock = mock$();
// setup beforeEach block to run before each test
beforeEach(() => {
// remember to always clear all mocks before each test
clearAllMocks();
});
// describe the 'on increment' test cases
describe("on increment", () => {
// describe the test case
it("should call onChange$", async () => {
// setup user event
const user = userEvent.setup();
// render the component into the DOM
await render(<Counter value={0} onChange$={onChangeMock}/>);
// retrieve the 'increment' button
const incrementBtn = screen.getByRole("button", {name: "Increment"});
// click the button
await user.click(incrementBtn);
// assert that the onChange$ callback was called with the right value
await waitFor(() =>
expect(onChangeMock).toHaveBeenCalledWith(1),
);
});
});
})You can also provide a default implementation to mock$:
const onSubmitMock = mock$(() => "success");
await render(<SubmitForm onSubmit$={onSubmitMock} />);
await user.click(screen.getByRole("button", { name: "Submit" }));
expect(await screen.findByText("success")).toBeInTheDocument();Qwik City - server$ calls
If one of your Qwik components uses server$ calls, your tests might fail with a rather cryptic message (e.g. QWIK
ERROR __vite_ssr_import_0__.myServerFunctionQrl is not a function or
QWIK ERROR Failed to parse URL from ?qfunc=DNpotUma33o).
We're happy to discuss it on Discord, but we consider this failure to be a good thing: your components should be tested in isolation, so you will be forced to mock your server functions.
Here is an example of how to test a component that uses server$ calls:
// ~/server/blog-posts.ts
import {server$} from "@builder.io/qwik-city";
import {BlogPost} from "~/lib/blog-post";
export const getLatestPosts$ = server$(function (): Promise<BlogPost> {
// get the latest posts
return Promise.resolve([]);
});// ~/components/latest-post-list.spec.tsx
import {render, screen, waitFor} from "@noma.to/qwik-testing-library";
import {LatestPostList} from "./latest-post-list";
vi.mock('~/server/blog-posts', () => ({
// the mocked function should end with `Qrl` instead of `$`
getLatestPostsQrl: () => {
return Promise.resolve([{id: 'post-1', title: 'Post 1'}, {id: 'post-2', title: 'Post 2'}]);
},
}));
describe('<LatestPostList />', () => {
it('should render the latest posts', async () => {
await render(<LatestPostList/>);
await waitFor(() => expect(screen.queryAllByRole('listitem')).toHaveLength(2));
});
});Notice how the mocked function is ending with Qrl instead of $, despite being named as getLatestPosts$.
This is caused by the Qwik optimizer renaming it to Qrl.
So, we need to mock the Qrl function instead of the original $ one.
If your function doesn't end with $, the Qwik optimizer will not rename it to Qrl.
Gotchas
- Watch mode (at least in Webstorm) doesn't seem to work well: components are not being updated with your latest changes
Issues
Looking to contribute? Look for the Good First Issue label.
🐛 Bugs
Please file an issue for bugs, missing documentation, or unexpected behavior.
💡 Feature Requests
Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.
❓ Questions
For questions related to using the library, please visit a support community instead of filing an issue on GitHub.
Contributors
Thanks goes to these people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!
Acknowledgements
Massive thanks to the Qwik Team and the whole community for their efforts to build Qwik and for the inspiration on how to create a testing library for Qwik.
Thanks to the Testing Library Team for a great set of tools to build better products, confidently, and qwikly.
