API
Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →
@testing-library/dom
Esta biblioteca reexporta tudo da DOM Testing Library
(@testing-library/dom). Consulte a documentação para ver
quais recursos você pode utilizar.
render
import {render} from '@testing-library/preact'
const {results} = render(<YourComponent />, {options})
Opções
| Option | Description | Default |
|---|---|---|
container | The HTML element the component is mounted to. | baseElement |
baseElement | The root HTML element to which the container is appended to. | document.body |
queries | Queries to bind to the baseElement. See within. | null |
hydrate | Used when the component has already been mounted and requires a rerender. Not needed for most people. The rerender function passed back to you does this already. | false |
wrapper | A parent component to wrap YourComponent. | null |
Resultados
| Result | Description |
|---|---|
container | The HTML element the component is mounted to. |
baseElement | The root HTML element to which the container is appended to. |
debug | Logs the baseElement using prettyDom. |
unmount | Unmounts the component from the container. |
rerender | Calls render again passing in the original arguments and sets hydrate to true. |
asFragment | Returns the innerHTML of the container. |
...queries | Returns all query functions to be used on the baseElement. If you pass in query arguments than this will be those, otherwise all. |
cleanup
Desmonta o componente do contêiner e destrói o contêiner.
Isso é chamado automaticamente se seu framework de testes (como Mocha, Jest ou Jasmine) injetar uma função global
afterEach()no ambiente de testes. Caso contrário, você precisará chamarcleanup()após cada teste.
Se desejar desativar esse comportamento, defina process.env.PTL_SKIP_AUTO_CLEANUP
como true ao executar seus testes.
import {render, cleanup} from '@testing-library/preact'
afterEach(() => {
cleanup()
}) // Default on import: runs it after each test.
render(<YourComponent />)
cleanup() // Or like this for more control.
act
É apenas uma exportação de conveniência que aponta para preact/test-utils/act. Todas as renderizações e
eventos disparados são encapsulados em act, então você realmente não precisa disso. Ele
é responsável por liberar todos os efeitos e rerenderizações após sua invocação.
📝 Se quiser aprender mais, confira esta explicação. Embora seja para React, ela dá uma ideia do motivo da necessidade.
fireEvent
Repassa para o fireEvent do @testing-library/dom.
Também é encapsulado em act, então você não precisa se preocupar em fazer isso.
📝 Lembre-se principalmente ao usar h / Preact.createElement que o React utiliza um
sistema de eventos sintéticos, enquanto o Preact usa o addEventListener nativo
do navegador para manipulação de eventos. Isso significa que eventos como onChange e onDoubleClick
no React correspondem a onInput e onDblClick no Preact. O exemplo de duplo clique
dará uma ideia de como testar usando essas funções.
Exemplo 1
const cb = jest.fn()
function Counter() {
useEffect(cb)
const [count, setCount] = useState(0)
return <button onClick={() => setCount(count + 1)}>{count}</button>
}
const {
container: {firstChild: buttonNode},
} = render(<Counter />)
// Clear the first call to useEffect that the initial render triggers.
cb.mockClear()
// Fire event Option 1.
fireEvent.click(buttonNode)
// Fire event Option 2.
fireEvent(
buttonNode,
new MouseEvent('click', {
bubbles: true,
cancelable: true,
button: 0,
}),
)
expect(buttonNode).toHaveTextContent('1')
expect(cb).toHaveBeenCalledTimes(1)
Exemplo 2
const handler = jest.fn()
const {
container: {firstChild: input},
} = render(<input type="text" onInput={handler} />)
fireEvent.input(input, {target: {value: 'a'}})
expect(handler).toHaveBeenCalledTimes(1)
Exemplo 3
const ref = createRef()
const spy = jest.fn()
render(
h(elementType, {
onDblClick: spy,
ref,
}),
)
fireEvent['onDblClick'](ref.current)
expect(spy).toHaveBeenCalledTimes(1)