Testcafe Testing Library
Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →
Introdução
testcafe-testing-library permite o uso de queries da DOM Testing Library
no Testcafe para testes web de ponta a ponta
e multiplataforma.
Se você é novo na abordagem testing-library para escrever testes, confira o guia sobre qual query usar e também o cheat sheet.
Instalação
- npm
- Yarn
npm install --save-dev testcafe @testing-library/testcafe
yarn add --dev testcafe @testing-library/testcafe
Como usar
testcafe-testing-library fornece seletores personalizados que permitem consultar
o DOM.
Adicione o seguinte ao seu arquivo .testcaferc.json:
"clientScripts": [
{ "module": "@testing-library/dom/dist/@testing-library/dom.umd.js" }
],
Agora você pode importar screen, que contém todos os seletores get[All]By, query[All]By,
e find[All]By* que podem ser usados em seus testes.
import {screen} from '@testing-library/testcafe'
Consulte Queries para referência
Observação sobre queries no Testcafe: O Testcafe possui espera integrada, portanto, não há diferença entre as queries
queryByefindByna testcafe testing library. QueriesgetBylançarão uma exceção (como projetado) e falharão imediatamente, não funcionando com a espera integrada do Testcafe.
Exemplos
Alguns exemplos simples (de https://github.com/testing-library/testcafe-testing-library/blob/master/tests/testcafe/selectors.ts):
import {screen} from '@testing-library/testcafe'
test('getByPlaceHolderText', async t => {
await t.typeText(
screen.getByPlaceholderText('Placeholder Text'),
'Hello Placeholder',
)
})
test('getByText', async t => {
await t.click(screen.getByText('getByText'))
})
test('getByLabelText', async t => {
await t.typeText(
screen.getByLabelText('Label For Input Labelled By Id'),
'Hello Input Labelled By Id',
)
})
test('queryAllByText', async t => {
await t.expect(screen.queryAllByText('Button Text').exists).ok()
await t
.expect(screen.queryAllByText('Non-existing Button Text').exists)
.notOk()
})
Configuração
Você pode personalizar o testIdAttribute usando a função configure da DOM Testing Library de várias formas:
Uma vez durante um carregamento de página único:
import {configureOnce, getByTestId} from '@testing-library/testcafe'
test('can be configured once in a single page load', async t => {
await configureOnce({testIdAttribute: 'data-other-test-id'})
await t.click(screen.getByTestId('other-id'))
})
Para cada teste e carregamento de página em um fixture:
import {configure, screen} from '@testing-library/testcafe'
fixture`configure`.clientScripts(
configure({testIdAttribute: 'data-automation-id'}),
).page`http://localhost:13370`
test('supports alternative testIdAttribute', async t => {
await t.click(screen.getByTestId('image-with-random-alt-tag'))
})
test('still works after browser page load and reload', async t => {
await t.click(screen.getByText('Go to Page 2'))
await t.eval(() => location.reload(true))
await t
.click(screen.getByTestId('page2-thing'))
.expect(screen.getByText('second page').exists)
.ok()
})
Globalmente para todos fixtures, testes e carregamentos de página injetando clientScripts
Observação: o UMD da dom-testing-library deve vir antes do seu script de configuração
"clientScripts": [
"./node_modules/@testing-library/dom/dist/@testing-library/dom.umd.js",
"./path/to/my-app-testcafe.config.js"
]
window.TestingLibraryDom.configure({testIdAttribute: 'data-automation-id'})
Containers
Por padrão, os seletores vêm pré-vinculados a document.body, então não é necessário
fornecer um container. Porém, se quiser restringir sua consulta usando um
container, use within, que aceita tanto uma string quanto uma query
(get[All]By, query[All]By, find[All]By*).
Exemplos usando within
import {within, screen} from '@testing-library/testcafe'
fixture`within`.page`http://localhost:13370`
test('works with getBy* selectors', async t => {
await t
.expect(
within(screen.getByTestId('nested')).getByText('Button Text').exists,
)
.ok()
})
test('works with CSS selector strings', async t => {
const {getByText} = await within('#nested')
await t.click(getByText('Button Text')).ok()
})
test('works on any testcafe selector', async t => {
const nested = Selector('#nested')
await t.expect(within(nested).getByText('Button Text').exists).ok()
})
test('works with results from "byAll" query with index - regex', async t => {
const nestedDivs = screen.getAllByTestId(/nested/)
await t.expect(nestedDivs.count).eql(2)
await t
.expect(within(nestedDivs.nth(0)).getByText('Button Text').exists)
.ok()
.expect(
within(nestedDivs.nth(1)).getByText('text only in 2nd nested').exists,
)
.ok()
})