Exemple
Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →
Voici quelques exemples d'utilisation de Qwik Testing Library pour tester vos composants Qwik.
Vous pouvez également approfondir vos connaissances sur les requêtes et les événements utilisateur pour vous aider à écrire vos tests.
Premiers pas
Voici une configuration minimale pour démarrer, avec des explications ligne par ligne.
// 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 - Appels server$
Si un de vos composants Qwik utilise des appels server$, vos tests peuvent échouer avec
un message plutôt cryptique (par exemple
QWIK ERROR __vite_ssr_import_0__.myServerFunctionQrl is not a function ou
QWIK ERROR Failed to parse URL from ?qfunc=DNpotUma33o).
Nous serons ravis d'en discuter sur Discord, mais nous considérons cet échec comme une bonne chose : vos composants doivent être testés de manière isolée, vous serez donc contraint de mocker vos fonctions serveur.
Voici un exemple pour tester un composant utilisant des appels server$ :
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)
})
})
Notez que la fonction mockée se termine par Qrl au lieu de $, bien qu'elle
soit nommée getLatestPosts$. Cela est dû au renommage en Qrl effectué par l'optimiseur Qwik.
Nous devons donc mocker la fonction Qrl plutôt que la fonction $ d'origine.
Si votre fonction ne se termine pas par $, l'optimiseur Qwik ne la renommera pas en
Qrl.