Saltar al contenido principal

APIs de utilidad

[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 →

Las siguientes APIs no tienen equivalentes directos en interacciones de usuario reales.
Su comportamiento interpreta cómo la interacción "percibida" del usuario podría traducirse a eventos reales en el DOM.

clear()

clear(element: Element): Promise<void>

Esta API permite borrar fácilmente un elemento editable.

  1. Enfoca el elemento

  2. Selecciona todo el contenido según el menú del navegador

  3. Elimina el contenido según el menú del navegador

test('clear', async () => {
const user = userEvent.setup()

render(<textarea defaultValue="Hello, World!" />)

await user.clear(screen.getByRole('textbox'))

expect(screen.getByRole('textbox')).toHaveValue('')
})

La Promise se rechaza si el elemento no puede enfocarse o el contenido no puede seleccionarse.

selectOptions(), deselectOptions()

selectOptions(
element: Element,
values: HTMLElement | HTMLElement[] | string[] | string,
): Promise<void>
deselectOptions(
element: Element,
values: HTMLElement | HTMLElement[] | string[] | string,
): Promise<void>

Selecciona/deselecciona las opciones especificadas en un HTMLSelectElement o listbox.

El parámetro values puede referirse a una opción por su valor, contenido HTML o directamente al elemento. También acepta arrays de estos valores.

Seleccionar múltiples opciones y/o deseleccionar opciones en HTMLSelectElement solo es posible si está especificado el atributo multiple.

test('selectOptions', async () => {
const user = userEvent.setup()

render(
<select multiple>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>,
)

await user.selectOptions(screen.getByRole('listbox'), ['1', 'C'])

expect(screen.getByRole('option', {name: 'A'}).selected).toBe(true)
expect(screen.getByRole('option', {name: 'B'}).selected).toBe(false)
expect(screen.getByRole('option', {name: 'C'}).selected).toBe(true)
})
test('deselectOptions', async () => {
const user = userEvent.setup()

render(
<select multiple>
<option value="1">A</option>
<option value="2" selected>
B
</option>
<option value="3">C</option>
</select>,
)

await user.deselectOptions(screen.getByRole('listbox'), '2')

expect(screen.getByText('B').selected).toBe(false)
})

Nota: esta API activa eventos de puntero y por tanto está sujeta a pointerEventsCheck.

type()

type(
element: Element,
text: KeyboardInput,
options?: {
skipClick?: boolean
skipAutoClose?: boolean
initialSelectionStart?: number
initialSelectionEnd?: number
}
): Promise<void>

Escribe en un elemento de entrada.

Debes usar keyboard() si solo quieres simular pulsaciones de teclas.
Usa type() si simplemente necesitas insertar texto convenientemente en campos de entrada o áreas de texto.

  1. A menos que skipClick sea true, hace clic en el elemento.

  2. Si initialSelectionStart está definido, establece la selección en el elemento. Si initialSelectionEnd no está definido, esto resulta en una selección colapsada.

  3. Escribe el text especificado mediante keyboard().

  4. A menos que skipAutoClose sea true, libera todas las teclas presionadas.

test('type into an input field', async () => {
const user = userEvent.setup()

render(<input defaultValue="Hello," />)
const input = screen.getByRole('textbox')

await user.type(input, ' World!')

expect(input).toHaveValue('Hello, World!')
})

upload()

upload(
element: HTMLElement,
fileOrFiles: File | File[],
): Promise<void>

Modifica un input de archivo como si el usuario hiciera clic y seleccionara archivos en el diálogo de carga resultante.

Los archivos que no coincidan con la propiedad accept se descartarán automáticamente, a menos que applyAccept esté configurado como false.

test('upload file', async () => {
const user = userEvent.setup()

render(
<div>
<label htmlFor="file-uploader">Upload file:</label>
<input id="file-uploader" type="file" />
</div>,
)
const file = new File(['hello'], 'hello.png', {type: 'image/png'})
const input = screen.getByLabelText(/upload file/i)

await user.upload(input, file)

expect(input.files[0]).toBe(file)
expect(input.files.item(0)).toBe(file)
expect(input.files).toHaveLength(1)
})

test('upload multiple files', async () => {
const user = userEvent.setup()

render(
<div>
<label htmlFor="file-uploader">Upload file:</label>
<input id="file-uploader" type="file" multiple />
</div>,
)
const files = [
new File(['hello'], 'hello.png', {type: 'image/png'}),
new File(['there'], 'there.png', {type: 'image/png'}),
]
const input = screen.getByLabelText(/upload file/i)

await user.upload(input, files)

expect(input.files).toHaveLength(2)
expect(input.files[0]).toBe(files[0])
expect(input.files[1]).toBe(files[1])
})