Saltar al contenido principal

Biblioteca de Testing para TestCafe

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

Introducción

testcafe-testing-library permite utilizar consultas de DOM Testing Library dentro de TestCafe para pruebas web de extremo a extremo multiplataforma.

Si eres nuevo en el enfoque testing-library para escribir pruebas, consulta la guía sobre qué consulta usar y la hoja de referencia.

Instalación

npm install --save-dev testcafe @testing-library/testcafe

Uso

testcafe-testing-library proporciona selectores personalizados que te permiten consultar el DOM.

Agrega lo siguiente a tu archivo .testcaferc.json:

  "clientScripts": [
{ "module": "@testing-library/dom/dist/@testing-library/dom.umd.js" }
],

Ahora puedes importar screen que contiene todos los selectores get[All]By, query[All]By, find[All]By* que puedes usar en tus pruebas.

import {screen} from '@testing-library/testcafe'

Consulta Queries como referencia

Nota sobre las consultas en TestCafe. TestCafe tiene espera integrada, por esto, no hay diferencia entre las consultas queryBy y findBy en testcafe testing library. Las consultas getBy lanzarán una excepción (como está diseñado) por lo que fallarán inmediatamente y no funcionan con la espera integrada que proporciona TestCafe.

Ejemplos

Para mostrar ejemplos simples (desde 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()
})

Configuración

Puedes personalizar testIdAttribute usando la función configure de DOM Testing Library de varias formas:

Una vez en una carga de página única:

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 prueba y carga de página en un 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, pruebas y cargas de página mediante inyección de clientScripts

Nota: el UMD de dom-testing-library debe ir antes de tu script de configuración

.testcaferc.json
  "clientScripts": [
"./node_modules/@testing-library/dom/dist/@testing-library/dom.umd.js",
"./path/to/my-app-testcafe.config.js"
]
./path/to/my-app-testcafe.config.js
window.TestingLibraryDom.configure({testIdAttribute: 'data-automation-id'})

Contenedores

Por defecto los selectores vienen pre-vinculados a document.body, así que no es necesario proporcionar un contenedor. Sin embargo, si quieres restringir tu consulta usando un contenedor, puedes usar within que acepta tanto una cadena como una consulta (get[All]By, query[All]By, find[All]By*).

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