Ir para o conteúdo principal

APIs utilitárias

[Tradução Beta Não Oficial]

Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →

As seguintes APIs não possuem equivalentes diretos em uma interação real do usuário.
Seu comportamento é uma interpretação de como a interação "percebida" pode ser traduzida em eventos reais no DOM.

clear()

clear(element: Element): Promise<void>

Esta API permite limpar facilmente um elemento editável.

  1. Foca no elemento

  2. Seleciona todo o conteúdo conforme o menu do navegador

  3. Exclui o conteúdo conforme o menu do navegador

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

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

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

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

A Promise é rejeitada se o elemento não puder ser focado ou o conteúdo não puder ser selecionado.

selectOptions(), deselectOptions()

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

Seleciona/desseleciona as opções fornecidas em um HTMLSelectElement ou listbox.

O parâmetro values pode referir-se a uma opção por seu valor, conteúdo HTML ou apenas fornecer o elemento. Também aceita um array desses valores.

Selecionar múltiplas opções e/ou desselecionar opções de HTMLSelectElement só é possível se o atributo multiple estiver especificado.

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

Observe que esta API dispara eventos de ponteiro e portanto está sujeita ao pointerEventsCheck.

type()

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

Digita em um elemento de input.

Use keyboard() para simular pressionamentos de teclas.
Use type() para inserir convenientemente texto em campos ou textareas.

  1. Clica no elemento, a menos que skipClick seja true.

  2. Se initialSelectionStart estiver definido, define a seleção no elemento. Se initialSelectionEnd não estiver definido, resulta em seleção colapsada.

  3. Digita o text fornecido via keyboard().

  4. Libera todas as teclas pressionadas, a menos que skipAutoClose seja true.

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>

Altera um input de arquivo como se o usuário clicasse e selecionasse arquivos na caixa de diálogo de upload.

Arquivos que não corresponderem à propriedade accept serão descartados automaticamente, a menos que applyAccept seja definido 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])
})