Saltar al contenido principal

API

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →


@testing-library/dom

Esta biblioteca reexporta todo desde DOM Testing Library (@testing-library/dom). Consulta la documentación para ver qué funcionalidades puedes utilizar.

render

import {render} from '@testing-library/preact'

const {results} = render(<YourComponent />, {options})

Opciones

OptionDescriptionDefault
containerThe HTML element the component is mounted to.baseElement
baseElementThe root HTML element to which the container is appended to.document.body
queriesQueries to bind to the baseElement. See within.null
hydrateUsed 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
wrapperA parent component to wrap YourComponent.null

Resultados

ResultDescription
containerThe HTML element the component is mounted to.
baseElementThe root HTML element to which the container is appended to.
debugLogs the baseElement using prettyDom.
unmountUnmounts the component from the container.
rerenderCalls render again passing in the original arguments and sets hydrate to true.
asFragmentReturns the innerHTML of the container.
...queriesReturns all query functions to be used on the baseElement. If you pass in query arguments than this will be those, otherwise all.

cleanup

Desmonta el componente del contenedor y destruye el contenedor.

Esto se llama automáticamente si tu framework de pruebas (como Mocha, Jest o Jasmine) inyecta una función global afterEach() en el entorno de pruebas. Si no es el caso, deberás llamar a cleanup() después de cada prueba.

Si deseas deshabilitar esto, establece process.env.PTL_SKIP_AUTO_CLEANUP como true al ejecutar tus pruebas.

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

Simplemente una exportación de conveniencia que apunta a preact/test-utils/act. Todos los renderizados y eventos disparados están envueltos en act, por lo que realmente no necesitas esto. Es responsable de liberar todos los efectos y rerenderizados después de invocarlo.

📝 Si quieres aprender más, revisa esta explicación. Aunque es para React, te da una idea de por qué se necesita.

fireEvent

Lo pasa al fireEvent de @testing-library/dom. También está envuelto en act, así que no necesitas preocuparte por hacerlo.

📝 Ten en cuenta principalmente al usar h / Preact.createElement que React utiliza un sistema de eventos sintéticos, mientras que Preact usa el addEventListener nativo del navegador para el manejo de eventos. Esto significa que eventos como onChange y onDoubleClick en React, son onInput y onDblClick en Preact. El ejemplo de doble clic te dará una idea de cómo probar usando esas funciones.

Ejemplo 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)

Ejemplo 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)

Ejemplo 3

const ref = createRef()
const spy = jest.fn()

render(
h(elementType, {
onDblClick: spy,
ref,
}),
)

fireEvent['onDblClick'](ref.current)

expect(spy).toHaveBeenCalledTimes(1)