Ejemplo
Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →
A continuación se muestran algunos ejemplos de cómo usar Qwik Testing Library para probar tus componentes Qwik.
También puedes obtener más información sobre las consultas y los eventos de usuario para ayudarte a escribir tus pruebas.
Qwikstart
Esta es una configuración mínima para que comiences, con explicaciones línea por línea.
// 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 - Llamadas server$
Si alguno de tus componentes Qwik utiliza llamadas server$, tus pruebas podrían fallar con un mensaje bastante críptico (por ejemplo, QWIK ERROR __vite_ssr_import_0__.myServerFunctionQrl is not a function o QWIK ERROR Failed to parse URL from ?qfunc=DNpotUma33o).
Estamos disponibles para discutirlo en Discord, pero consideramos que este fallo es positivo: tus componentes deben probarse de forma aislada, por lo que te verás obligado a simular tus funciones de servidor.
Aquí tienes un ejemplo de cómo probar un componente que utiliza llamadas 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)
})
})
Observa cómo la función simulada termina con Qrl en lugar de $, a pesar de llamarse getLatestPosts$. Esto se debe a que el optimizador de Qwik la renombra a Qrl. Por lo tanto, necesitamos simular la función Qrl en lugar de la original con $.
Si tu función no termina con $, el optimizador de Qwik no la renombrará a Qrl.