Exemplo
Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →
A seguir, exemplos de como usar a Qwik Testing Library para testar seus componentes Qwik.
Você também pode aprender mais sobre as consultas e eventos de usuário para ajudar a escrever seus testes.
Qwikstart
Esta é uma configuração mínima para você começar, com explicações linha por linha.
// 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 - Chamadas server$
Se algum componente Qwik usar chamadas server$, seus testes podem falhar com mensagens crípticas (ex: QWIK ERROR __vite_ssr_import_0__.myServerFunctionQrl is not a function ou QWIK ERROR Failed to parse URL from ?qfunc=DNpotUma33o).
Estamos abertos para discutir no Discord, mas consideramos essa falha positiva: seus componentes devem ser testados isoladamente, então você precisará simular (mock) as funções de servidor.
Aqui está um exemplo de como testar um componente que usa chamadas 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)
})
})
Note que a função simulada termina com Qrl em vez de $, mesmo sendo nomeada como getLatestPosts$. Isso ocorre porque o otimizador do Qwik renomeia para Qrl. Portanto, devemos simular a função Qrl em vez da original com $.
Se sua função não terminar com $, o otimizador do Qwik não a renomeará para Qrl.