API
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 →
@testing-library/dom
Cette bibliothèque réexporte tous les éléments de la DOM Testing Library
(@testing-library/dom). Consultez la documentation pour découvrir
les fonctionnalités disponibles.
render
import {render} from '@testing-library/preact'
const {results} = render(<YourComponent />, {options})
Options
| 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 |
Résultats
| 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
Démonte le composant de son conteneur et détruit ce dernier.
Appelé automatiquement si votre framework de test (comme Mocha, Jest ou Jasmine) injecte une fonction globale
afterEach(). Sinon, vous devez appelercleanup()après chaque test.
Pour désactiver ce comportement, définissez process.env.PTL_SKIP_AUTO_CLEANUP sur
true lors de l'exécution de vos tests.
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
Simple export de commodité pointant vers preact/test-utils/act. Tous les rendus et
événements déclenchés sont encapsulés dans act, vous n'en avez donc pas réellement besoin.
Il est responsable du vidage de tous les effets et des rerender après son invocation.
📝 Pour approfondir le sujet, consultez cette explication. Bien qu'elle concerne React, elle vous donne une idée de sa nécessité.
fireEvent
Transmet l'événement à la fonction fireEvent
de @testing-library/dom. Elle est également encapsulée dans act, vous n'avez donc
pas à vous soucier de le faire.
📝 Notez bien qu'avec h / Preact.createElement, React utilise un système d'événements
synthétiques tandis que Preact utilise le addEventListener natif du navigateur.
Ainsi, les événements onChange et onDoubleClick dans React correspondent à
onInput et onDblClick dans Preact. L'exemple du double-clic vous montrera comment
tester ces fonctions.
Exemple 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)
Exemple 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)
Exemple 3
const ref = createRef()
const spy = jest.fn()
render(
h(elementType, {
onDblClick: spy,
ref,
}),
)
fireEvent['onDblClick'](ref.current)
expect(spy).toHaveBeenCalledTimes(1)