Saltar al contenido principal

Configuración

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

Este módulo se distribuye mediante npm, que viene incluido con node, y debe instalarse como una de las devDependencies de tu proyecto:

npm install --save-dev @noma.to/qwik-testing-library @testing-library/dom

Esta biblioteca es compatible con versiones de qwik 1.7.2 o superiores y versiones de @testing-library/dom 10.1.0 o superiores.

También te puede interesar instalar @testing-library/jest-dom y @testing-library/user-event para usar los matchers personalizados de jest y la biblioteca de eventos de usuario al probar interacciones con el DOM.

npm install --save-dev @testing-library/jest-dom @testing-library/user-event

Finalmente, necesitamos un entorno DOM para ejecutar las pruebas. Esta biblioteca se ha probado con jsdom y happy-dom:

npm install --save-dev jsdom

o

npm install --save-dev happy-dom

Configuración de Vitest

Recomendamos usar @noma.to/qwik-testing-library con Vitest como ejecutor de pruebas.

Si aún no lo has hecho, agrega vitest a tu proyecto usando Qwik CLI:

npm run qwik add vitest

Luego, debemos configurar Vitest para que pueda ejecutar tus pruebas. Para ello, crea un archivo vitest.config.ts separado para no modificar el vite.config.ts de tu proyecto:

vitest.config.ts
import {defineConfig, mergeConfig} from 'vitest/config'
import viteConfig from './vite.config'

export default defineConfig(configEnv =>
mergeConfig(
viteConfig(configEnv),
defineConfig({
// qwik-testing-library needs to consider your project as a Qwik lib
// if it's already a Qwik lib, you can remove this section
build: {
target: 'es2020',
lib: {
entry: './src/index.ts',
formats: ['es', 'cjs'],
fileName: (format, entryName) =>
`${entryName}.qwik.${format === 'es' ? 'mjs' : 'cjs'}`,
},
},
// configure your test environment
test: {
environment: 'jsdom', // or 'happy-dom'
setupFiles: ['./vitest.setup.ts'],
globals: true,
},
}),
),
)

Por ahora, qwik-testing-library necesita considerar tu proyecto como una librería. De ahí la sección build.lib en la configuración anterior.

Como el proceso de compilación intentará usar ./src/index.ts como punto de entrada, necesitamos crearlo:

src/index.ts
/**
* DO NOT DELETE THIS FILE
*
* This entrypoint is needed by @noma.to/qwik-testing-library to run your tests
*/

Luego, crea el archivo vitest.setup.ts:

vitest.setup.ts
// Configure DOM matchers to work in Vitest
import '@testing-library/jest-dom/vitest'

// This has to run before qdev.ts loads. `beforeAll` is too late
globalThis.qTest = false // Forces Qwik to run as if it was in a Browser
globalThis.qRuntimeQrl = true
globalThis.qDev = true
globalThis.qInspector = false

Esta configuración asegurará que Qwik esté correctamente configurado. También carga @testing-library/jest-dom/vitest en tu ejecutor de pruebas para que puedas usar matchers como expect(...).toBeInTheDocument().

Por defecto, Qwik Testing Library limpia todo automáticamente. Puedes desactivar este comportamiento estableciendo la variable de entorno QTL_SKIP_AUTO_CLEANUP en true. Luego, en tus pruebas podrás llamar a la función cleanup cuando sea necesario. Por ejemplo:

import {cleanup} from '@noma.to/qwik-testing-library'
import {afterEach} from 'vitest'

afterEach(cleanup)

Ahora, edita tu tsconfig.json para declarar los siguientes tipos globales:

tsconfig.json
{
"compilerOptions": {
"types": [
+ "vitest/globals",
+ "@testing-library/jest-dom/vitest"
]
},
"include": ["src"]
}

Finalmente, puedes agregar scripts de prueba a tu package.json para ejecutar las pruebas con Vitest

package.json
{
"scripts": {
"test": "vitest run",
"test:ui": "vitest --ui",
"test:watch": "vitest"
}
}