Skip to content

Latest commit

 

History

History
103 lines (81 loc) · 3.13 KB

File metadata and controls

103 lines (81 loc) · 3.13 KB
idtitlesidebar_label
example
Example
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 methodsimport{screen,render,waitFor}from'@noma.to/qwik-testing-library'// import the userEvent methods to interact with the DOMimport{userEvent}from'@testing-library/user-event'// import the component to be testedimport{Counter}from'./counter'// describe the test suitedescribe('<Counter />',()=>{// describe the test caseit('should increment the counter',async()=>{// setup user eventconstuser=userEvent.setup()// render the component into the DOMawaitrender(<Counter/>)// retrieve the 'increment count' buttonconstincrementBtn=screen.getByRole('button',{name: /incrementcount/})// click the button twiceawaituser.click(incrementBtn)awaituser.click(incrementBtn)// assert that the counter is now 2expect(awaitscreen.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'exportconstgetLatestPosts$=server$(function(): Promise<BlogPost>{// get the latest postsreturnPromise.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: ()=>{returnPromise.resolve([{id: 'post-1',title: 'Post 1'},{id: 'post-2',title: 'Post 2'},])},}))describe('<LatestPostList />',()=>{it('should render the latest posts',async()=>{awaitrender(<LatestPostList/>)expect(awaitscreen.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.

close