Example
Below are some examples of how to use the Qwik Testing Library to test your Qwik components.
You can also learn more about the queries and user events to help you write your tests.
Qwikstart
This is a minimal setup to get you started, with line-by-line explanations.
// 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()
})
})
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:
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([])
})
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 />)
expect(await screen.findAllByRole('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
.