Configuração
Esta página foi traduzida por PageTurner AI (beta). Não é oficialmente endossada pelo projeto. Encontrou um erro? Reportar problema →
Este módulo é distribuído via npm, que vem integrado com node, e
deve ser instalado como uma das suas devDependencies no projeto:
- npm
- Yarn
npm install --save-dev @noma.to/qwik-testing-library @testing-library/dom
yarn add --dev @noma.to/qwik-testing-library @testing-library/dom
Esta biblioteca é compatível com versões 1.7.2 ou superiores do qwik e
versões 10.1.0 ou superiores do @testing-library/dom.
Você também pode instalar @testing-library/jest-dom e
@testing-library/user-event para usar os matchers personalizados do jest
e a biblioteca de eventos de usuário ao testar
interações com o DOM.
- npm
- Yarn
npm install --save-dev @testing-library/jest-dom @testing-library/user-event
yarn add --dev @testing-library/jest-dom @testing-library/user-event
Por fim, precisamos de um ambiente DOM para executar os testes. Esta biblioteca foi testada tanto com jsdom quanto com happy-dom:
- npm
- Yarn
npm install --save-dev jsdom
yarn add --dev jsdom
ou
- npm
- Yarn
npm install --save-dev happy-dom
yarn add --dev happy-dom
Configuração do Vitest
Recomendamos usar @noma.to/qwik-testing-library com Vitest como
executor de testes.
Se ainda não fez isso, adicione o Vitest ao seu projeto usando a CLI do Qwik:
- npm
- Yarn
npm run qwik add vitest
yarn run qwik add vitest
Depois, precisamos configurar o Vitest para executar seus testes. Para isso,
crie um arquivo vitest.config.ts separado, evitando alterar o
vite.config.ts do projeto:
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,
},
}),
),
)
Atualmente, o qwik-testing-library precisa tratar seu projeto como uma biblioteca.
Por isso, a seção build.lib na configuração acima.
Como o build tentará usar ./src/index.ts como ponto de entrada, precisamos
criar esse arquivo:
/**
* DO NOT DELETE THIS FILE
*
* This entrypoint is needed by @noma.to/qwik-testing-library to run your tests
*/
Em seguida, crie o arquivo 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
Essa configuração garantirá que o Qwik seja inicializado corretamente. Ela também
carrega @testing-library/jest-dom/vitest no executor de testes, permitindo usar
matchers como expect(...).toBeInTheDocument().
Por padrão, o Qwik Testing Library faz limpeza automática de tudo após os testes.
Você pode desativar isso definindo a variável de ambiente QTL_SKIP_AUTO_CLEANUP
como true. Nos seus testes, chame manualmente a função cleanup quando necessário.
Exemplo:
import {cleanup} from '@noma.to/qwik-testing-library'
import {afterEach} from 'vitest'
afterEach(cleanup)
Agora, edite seu tsconfig.json para declarar os seguintes tipos globais:
{
"compilerOptions": {
"types": [
+ "vitest/globals",
+ "@testing-library/jest-dom/vitest"
]
},
"include": ["src"]
}
Por fim, adicione scripts de teste no seu package.json para executar os testes
com Vitest:
{
"scripts": {
"test": "vitest run",
"test:ui": "vitest --ui",
"test:watch": "vitest"
}
}