create-codeverse 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/templates.js CHANGED
@@ -6,7 +6,8 @@ import { applyTestComponentes, applyTestDependencias } from './apply/test.js';
6
6
  // fim do menu, independente da ordem alfabética. `ready: false` mostra o aviso
7
7
  // de "em breve" em vez de seguir para as perguntas do template.
8
8
  // `options` (opcional) vira um multiselect de extras. Cada `id` é a mesma chave
9
- // usada no bloco do template em templates/versions.json.
9
+ // usada no bloco do template em templates/versions.json; um extra com `versions`
10
+ // usa essa lista de blocos no lugar (ex.: Ant Design).
10
11
  // `apply(projectDir, optionIds)` (opcional) altera o código do projeto copiado
11
12
  // conforme os extras marcados. A pasta do template é templates/<id>.
12
13
  // `choice: true` troca o multiselect por um select de sub-templates: cada item
@@ -19,12 +20,18 @@ export const templates = [
19
20
  hint: 'NextJS App Router',
20
21
  ready: true,
21
22
  apply: applyFront,
23
+ versions: ['front.base', 'front.compiler'],
22
24
  options: [
23
- { id: 'antd', label: 'Ant Design', hint: 'componentes UI' },
25
+ {
26
+ id: 'antd',
27
+ label: 'Ant Design',
28
+ hint: 'componentes UI',
29
+ versions: ['front.antd', 'front.antdRegistry'],
30
+ },
24
31
  { id: 'axios', label: 'Axios', hint: 'requisições HTTP' },
25
- { id: 'lucide', label: 'Lucide Icons', hint: 'ícones' },
32
+ { id: 'lucide', label: 'Lucide React', hint: 'ícones' },
26
33
  { id: 'tailwind', label: 'TailwindCss', hint: 'estilização CSS' },
27
- { id: 'toast', label: 'Toast-Hot', hint: 'notificações' },
34
+ { id: 'toast', label: 'React-Hot-Toast', hint: 'notificações' },
28
35
  ],
29
36
  },
30
37
  { id: 'backend', label: 'BackEnd', hint: 'NodeJS Express', ready: false },
@@ -59,7 +66,7 @@ export const templates = [
59
66
  hint: 'Cypress - componentes React',
60
67
  ready: true,
61
68
  dir: 'front',
62
- versions: ['front.base', 'test.cypress.base'],
69
+ versions: ['front.base', 'front.compiler', 'test.cypress.base'],
63
70
  apply: applyTestComponentes,
64
71
  },
65
72
  {
@@ -74,6 +81,17 @@ export const templates = [
74
81
  },
75
82
  // `secret: true`: o template fica criptografado em templates/<id>.enc e só
76
83
  // abre com o código secreto (ver lib/secret.js e scripts/encrypt.js). Só os
77
- // arquivos são secretos: as versões ficam no versions.json (bloco "codeskills.base").
78
- { id: 'codeskills', label: 'CodeSkills', hint: 'FullStack', ready: true, last: true, secret: true },
84
+ // arquivos são secretos: as versões ficam no versions.json.
85
+ // `versions` (opcional, sem `choice`): lista de blocos do versions.json no lugar
86
+ // do "<id>.base". Aqui, a base do front (sem o React Compiler, que fica em
87
+ // "front.compiler") + os pacotes próprios do CodeSkills.
88
+ {
89
+ id: 'codeskills',
90
+ label: 'CodeSkills',
91
+ hint: 'FullStack',
92
+ ready: true,
93
+ last: true,
94
+ secret: true,
95
+ versions: ['front.base', 'front.antd', 'codeskills.base'],
96
+ },
79
97
  ];
@@ -1,24 +1,24 @@
1
- const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
2
- const MAX_LENGTH = 214;
3
-
4
- export function validateProjectName(raw) {
5
- const value = String(raw ?? '').trim();
6
-
7
- if (!value) {
8
- return { valid: false, message: 'O nome do projeto não pode ser vazio, fera ...' };
9
- }
10
-
11
- if (value.length > MAX_LENGTH) {
12
- return { valid: false, message: `Nome muito longo (máx. ${MAX_LENGTH} caracteres).` };
13
- }
14
-
15
- if (!NAME_PATTERN.test(value)) {
16
- return {
17
- valid: false,
18
- message:
19
- 'Nome inválido. Use apenas letras minúsculas, números e hífen (sem espaços, sem começar ou terminar com hífen).',
20
- };
21
- }
22
-
23
- return { valid: true, value };
24
- }
1
+ const NAME_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
2
+ const MAX_LENGTH = 214;
3
+
4
+ export function validateProjectName(raw) {
5
+ const value = String(raw ?? '').trim();
6
+
7
+ if (!value) {
8
+ return { valid: false, message: 'O nome do projeto não pode ser vazio, fera ...' };
9
+ }
10
+
11
+ if (value.length > MAX_LENGTH) {
12
+ return { valid: false, message: `Nome muito longo (máx. ${MAX_LENGTH} caracteres).` };
13
+ }
14
+
15
+ if (!NAME_PATTERN.test(value)) {
16
+ return {
17
+ valid: false,
18
+ message:
19
+ 'Nome inválido. Use apenas letras minúsculas, números e hífen (sem espaços, sem começar ou terminar com hífen).',
20
+ };
21
+ }
22
+
23
+ return { valid: true, value };
24
+ }
package/lib/versions.js CHANGED
@@ -1,50 +1,110 @@
1
- import { readFile } from 'node:fs/promises';
2
- import { join } from 'node:path';
3
-
4
- import { TEMPLATES_DIR } from './paths.js';
5
-
6
- const GROUPS = ['dependencies', 'devDependencies'];
7
-
8
- function sortByName(object) {
9
- return Object.fromEntries(Object.entries(object).sort(([a], [b]) => a.localeCompare(b)));
10
- }
11
-
12
- function findBlock(all, blockPath) {
13
- const block = blockPath.split('.').reduce((node, key) => node?.[key], all);
14
- if (!block) {
15
- throw new Error(`Bloco "${blockPath}" não encontrado em versions.json.`);
16
- }
17
- return block;
18
- }
19
-
20
- // Lê templates/versions.json e junta os blocos pedidos em `blockPaths` (caminhos
21
- // separados por ponto, ex.: "front.base", "test.cypress.base"). Cada bloco pode
22
- // ser reaproveitado por outros templates, sem repetir os pacotes. Devolve:
23
- // pinned: { dependencies: { nome: 'X.Y.Z' }, devDependencies: {...} }
24
- // versão fixada, vai direto para o package.json do aluno
25
- // latest: { dependencies: ['nome'], devDependencies: [...] }
26
- // valor "latest", instalado depois com `npm install <nome>@latest`
27
- export async function resolvePackages(blockPaths) {
28
- const all = JSON.parse(await readFile(join(TEMPLATES_DIR, 'versions.json'), 'utf8'));
29
-
30
- const pinned = { dependencies: {}, devDependencies: {} };
31
- const latest = { dependencies: new Set(), devDependencies: new Set() };
32
-
33
- for (const blockPath of blockPaths) {
34
- const block = findBlock(all, blockPath);
35
- for (const group of GROUPS) {
36
- for (const [name, version] of Object.entries(block[group] ?? {})) {
37
- if (version === 'latest') latest[group].add(name);
38
- else pinned[group][name] = version;
39
- }
40
- }
41
- }
42
-
43
- const sortedLatest = {};
44
- for (const group of GROUPS) {
45
- pinned[group] = sortByName(pinned[group]);
46
- sortedLatest[group] = [...latest[group]].sort((a, b) => a.localeCompare(b));
47
- }
48
-
49
- return { pinned, latest: sortedLatest };
50
- }
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ import { TEMPLATES_DIR } from './paths.js';
5
+
6
+ const GROUPS = ['dependencies', 'devDependencies'];
7
+
8
+ function sortByName(object) {
9
+ return Object.fromEntries(Object.entries(object).sort(([a], [b]) => a.localeCompare(b)));
10
+ }
11
+
12
+ function findBlock(all, blockPath) {
13
+ const block = blockPath.split('.').reduce((node, key) => node?.[key], all);
14
+ if (!block) {
15
+ throw new Error(`Bloco "${blockPath}" não encontrado em versions.json.`);
16
+ }
17
+ return block;
18
+ }
19
+
20
+ // Lê templates/versions.json e junta os blocos pedidos em `blockPaths` (caminhos
21
+ // separados por ponto, ex.: "front.base", "test.cypress.base"). Cada bloco pode
22
+ // ser reaproveitado por outros templates, sem repetir os pacotes. Devolve:
23
+ // pinned: { dependencies: { nome: 'X.Y.Z' }, devDependencies: {...} }
24
+ // versão fixada, vai direto para o package.json do aluno
25
+ // latest: { dependencies: ['nome'], devDependencies: [...] }
26
+ // valor "latest", instalado depois com `npm install <nome>@latest`
27
+ export async function resolvePackages(blockPaths) {
28
+ const all = JSON.parse(await readFile(join(TEMPLATES_DIR, 'versions.json'), 'utf8'));
29
+
30
+ const pinned = { dependencies: {}, devDependencies: {} };
31
+ const latest = { dependencies: new Set(), devDependencies: new Set() };
32
+
33
+ for (const blockPath of blockPaths) {
34
+ const block = findBlock(all, blockPath);
35
+ for (const group of GROUPS) {
36
+ for (const [name, version] of Object.entries(block[group] ?? {})) {
37
+ if (version === 'latest') latest[group].add(name);
38
+ else pinned[group][name] = version;
39
+ }
40
+ }
41
+ }
42
+
43
+ const sortedLatest = {};
44
+ for (const group of GROUPS) {
45
+ pinned[group] = sortByName(pinned[group]);
46
+ sortedLatest[group] = [...latest[group]].sort((a, b) => a.localeCompare(b));
47
+ }
48
+
49
+ return { pinned, latest: sortedLatest };
50
+ }
51
+
52
+ const REGISTRY = 'https://registry.npmjs.org';
53
+ const REGISTRY_TIMEOUT_MS = 10_000;
54
+
55
+ // Versão marcada como "latest" no registry, a mesma que `npm install <nome>@latest` instala.
56
+ async function fetchLatestVersion(name) {
57
+ const response = await fetch(`${REGISTRY}/${name}/latest`, {
58
+ signal: AbortSignal.timeout(REGISTRY_TIMEOUT_MS),
59
+ });
60
+ if (!response.ok) throw new Error(`Registry respondeu ${response.status} para ${name}.`);
61
+ const { version } = await response.json();
62
+ if (!version) throw new Error(`Registry não informou a versão de ${name}.`);
63
+ return version;
64
+ }
65
+
66
+ // Troca os pacotes "latest" por `^X.Y.Z` (o mesmo formato que o npm grava com
67
+ // @latest) e junta tudo em `pinned`, para o package.json já sair completo e bastar
68
+ // um único `npm install`. As consultas ao registry rodam em paralelo. Se alguma
69
+ // falhar (sem internet, proxy), devolve null e o CLI segue com os `@latest`.
70
+ export async function pinLatestVersions({ pinned, latest }) {
71
+ try {
72
+ const groups = await Promise.all(
73
+ GROUPS.map(async (group) => {
74
+ const entries = await Promise.all(
75
+ latest[group].map(async (name) => [name, `^${await fetchLatestVersion(name)}`]),
76
+ );
77
+ return [group, sortByName({ ...pinned[group], ...Object.fromEntries(entries) })];
78
+ }),
79
+ );
80
+ return {
81
+ pinned: Object.fromEntries(groups),
82
+ latest: { dependencies: [], devDependencies: [] },
83
+ };
84
+ } catch {
85
+ return null;
86
+ }
87
+ }
88
+
89
+ // Junta os blocos e já troca os "latest" pela versão do registry. Sem acesso ao
90
+ // registry, devolve os "latest" como estão (o CLI instala com `@latest`).
91
+ // O CLI chama assim que cada pergunta do menu é respondida, e a consulta roda
92
+ // em segundo plano enquanto o aluno responde as próximas.
93
+ export async function prepareVersions(blockPaths) {
94
+ const resolved = await resolvePackages(blockPaths);
95
+ return (await pinLatestVersions(resolved)) ?? resolved;
96
+ }
97
+
98
+ // Junta vários resultados de `prepareVersions` em um só (mesmo formato).
99
+ // Um pacote com versão em `pinned` sai da lista `latest`.
100
+ export function mergePackages(results) {
101
+ const pinned = {};
102
+ const latest = {};
103
+ for (const group of GROUPS) {
104
+ pinned[group] = sortByName(Object.assign({}, ...results.map((item) => item.pinned[group])));
105
+ latest[group] = [...new Set(results.flatMap((item) => item.latest[group]))]
106
+ .filter((name) => !(name in pinned[group]))
107
+ .sort((a, b) => a.localeCompare(b));
108
+ }
109
+ return { pinned, latest };
110
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-codeverse",
3
- "version": "0.0.1",
3
+ "version": "0.1.0",
4
4
  "description": "Scaffolding CLI for Codeverse students to learn",
5
5
  "type": "module",
6
6
  "bin": {
@@ -42,5 +42,8 @@
42
42
  "license": "MIT",
43
43
  "dependencies": {
44
44
  "@clack/prompts": "1.9.0"
45
- }
45
+ },
46
+ "bundleDependencies": [
47
+ "@clack/prompts"
48
+ ]
46
49
  }
Binary file
@@ -0,0 +1,44 @@
1
+ # Projeto de Testes de Componentes — Cypress + Next.js
2
+
3
+ Projeto criado com o `create-codeverse`: Next.js (App Router) com o Cypress Component Testing, para
4
+ testar componentes React isolados.
5
+
6
+ ## Como rodar os testes
7
+
8
+ | Passo | Comando |
9
+ |---|---|
10
+ | Abrir o terminal do VS Code | `` Ctrl + ` `` |
11
+ | Abrir o Cypress | `npm test` |
12
+ | No Cypress | Escolha **Component Testing**, depois um navegador, depois o teste `Login.cy.jsx` |
13
+
14
+ ## Scripts
15
+
16
+ | Comando | O que faz |
17
+ |---|---|
18
+ | `npm test` | Abre o Cypress |
19
+ | `npm run dev` | Roda o projeto em [http://localhost:3000](http://localhost:3000) |
20
+ | `npm run lint` | Confere o código e a formatação com o Biome |
21
+ | `npm run format` | Formata todos os arquivos |
22
+ | `npm run clean` | Apaga do PC as versões antigas do programa Cypress (cerca de 200 MB cada), mantendo só a usada neste projeto |
23
+
24
+ ## Estrutura
25
+
26
+ | Pasta / arquivo | Para que serve |
27
+ |---|---|
28
+ | `src/components/Login.jsx` | Componente testado |
29
+ | `src/app/page.jsx` | Página que mostra o `Login` |
30
+ | `cypress/component/Login.cy.jsx` | Teste do componente, com um exemplo de cada tipo de verificação |
31
+ | `cypress/fixtures/` | Dados de exemplo para os testes |
32
+ | `cypress/support/` | Arquivos de apoio do Cypress |
33
+ | `cypress.config.js` | Configuração do Cypress (Component Testing com Next.js) |
34
+
35
+ Pastas `cypress/screenshots/`, `cypress/videos/` e `cypress/downloads/` são geradas pelo Cypress e
36
+ ficam fora do Git (`.gitignore`).
37
+
38
+ ## Para saber mais
39
+
40
+ | Assunto | Link |
41
+ |---|---|
42
+ | Cypress Component Testing | [docs.cypress.io](https://docs.cypress.io/app/core-concepts/testing-types#What-is-Component-Testing) |
43
+ | Next.js | [nextjs.org/docs](https://nextjs.org/docs) |
44
+ | Material da CodeVerse | [codeverse.dev.br](https://codeverse.dev.br) |
@@ -1,36 +1,51 @@
1
- This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).
2
-
3
- ## Getting Started
4
-
5
- First, run the development server:
6
-
7
- ```bash
8
- npm run dev
9
- # or
10
- yarn dev
11
- # or
12
- pnpm dev
13
- # or
14
- bun dev
15
- ```
16
-
17
- Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
18
-
19
- You can start editing the page by modifying `app/page.js`. The page auto-updates as you edit the file.
20
-
21
- This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
22
-
23
- ## Learn More
24
-
25
- To learn more about Next.js, take a look at the following resources:
26
-
27
- - [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
28
- - [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
29
-
30
- You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
31
-
32
- ## Deploy on Vercel
33
-
34
- The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
35
-
36
- Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
1
+ # Projeto FrontEnd — Next.js
2
+
3
+ Projeto criado com o `create-codeverse`: Next.js (App Router) com React, React Compiler e Biome.
4
+
5
+ ## Como rodar
6
+
7
+ | Passo | Comando |
8
+ |---|---|
9
+ | Abrir o terminal do VS Code | `` Ctrl + ` `` |
10
+ | Rodar o projeto | `npm run dev` |
11
+ | Ver no navegador | [http://localhost:3000](http://localhost:3000) |
12
+ | Parar o projeto | `Ctrl + C` no terminal |
13
+
14
+ ## Scripts
15
+
16
+ | Comando | O que faz |
17
+ |---|---|
18
+ | `npm run dev` | Limpa o terminal e inicia o servidor de desenvolvimento |
19
+ | `npm run lint` | Confere o código e a formatação com o Biome |
20
+ | `npm run format` | Formata todos os arquivos |
21
+
22
+ ## Estrutura
23
+
24
+ | Pasta / arquivo | Para que serve |
25
+ |---|---|
26
+ | `src/app/page.jsx` | Página inicial (`/`) |
27
+ | `src/app/layout.js` | Estrutura comum a todas as páginas (`<html>`, `<body>`) |
28
+ | `src/app/globals.css` | Estilos globais |
29
+ | `src/app/nome-da-rota/` | Exemplo de rota: renomeie a pasta e ela vira o endereço (ex.: `src/app/sobre/` → `/sobre`) |
30
+ | `src/components/` | Componentes reaproveitáveis (exemplo: `Nome-do-componente.jsx`) |
31
+ | `public/` | Arquivos estáticos: `fonts`, `icons`, `images`, `media`, `sounds` |
32
+ | `.env.example` | Modelo das variáveis de ambiente: copie para `.env` e preencha |
33
+ | `biome.json` | Regras de formatação e de lint |
34
+ | `jsconfig.json` | Atalhos de importação |
35
+ | `next.config.mjs` | Configuração do Next.js (React Compiler ligado) |
36
+
37
+ ## Atalhos de importação
38
+
39
+ | Atalho | Aponta para | Exemplo |
40
+ |---|---|---|
41
+ | `@/` | `src/` | `import Botao from '@/components/Botao';` |
42
+ | `@components/` | `src/components/` | `import Botao from '@components/Botao';` |
43
+
44
+ ## Para saber mais
45
+
46
+ | Assunto | Link |
47
+ |---|---|
48
+ | Next.js | [nextjs.org/docs](https://nextjs.org/docs) |
49
+ | React | [react.dev](https://react.dev) |
50
+ | Biome | [biomejs.dev](https://biomejs.dev) |
51
+ | Material da CodeVerse | [codeverse.dev.br](https://codeverse.dev.br) |
@@ -1,42 +1,42 @@
1
- {
2
- "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",
3
- "vcs": {
4
- "enabled": true,
5
- "clientKind": "git",
6
- "useIgnoreFile": true
7
- },
8
- "files": {
9
- "ignoreUnknown": true,
10
- "includes": ["**", "!node_modules", "!.next", "!dist", "!build"]
11
- },
12
- "formatter": {
13
- "enabled": true,
14
- "indentStyle": "space",
15
- "indentWidth": 4
16
- },
17
- "javascript": {
18
- "formatter": {
19
- "quoteStyle": "single"
20
- }
21
- },
22
- "linter": {
23
- "enabled": true,
24
- "rules": {
25
- "recommended": true,
26
- "suspicious": {
27
- "noUnknownAtRules": "off"
28
- }
29
- },
30
- "domains": {
31
- "next": "recommended",
32
- "react": "recommended"
33
- }
34
- },
35
- "assist": {
36
- "actions": {
37
- "source": {
38
- "organizeImports": "on"
39
- }
40
- }
41
- }
42
- }
1
+ {
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
+ "vcs": {
4
+ "enabled": true,
5
+ "clientKind": "git",
6
+ "useIgnoreFile": true
7
+ },
8
+ "files": {
9
+ "ignoreUnknown": true,
10
+ "includes": ["**", "!node_modules", "!.next", "!dist", "!build"]
11
+ },
12
+ "formatter": {
13
+ "enabled": true,
14
+ "indentStyle": "space",
15
+ "indentWidth": 4
16
+ },
17
+ "javascript": {
18
+ "formatter": {
19
+ "quoteStyle": "single"
20
+ }
21
+ },
22
+ "linter": {
23
+ "enabled": true,
24
+ "rules": {
25
+ "preset": "recommended",
26
+ "suspicious": {
27
+ "noUnknownAtRules": "off"
28
+ }
29
+ },
30
+ "domains": {
31
+ "next": "recommended",
32
+ "react": "recommended"
33
+ }
34
+ },
35
+ "assist": {
36
+ "actions": {
37
+ "source": {
38
+ "organizeImports": "on"
39
+ }
40
+ }
41
+ }
42
+ }
@@ -1,11 +1,11 @@
1
- import { fileURLToPath } from 'node:url';
2
-
3
- /** @type {import('next').NextConfig} */
4
- const nextConfig = {
5
- reactCompiler: true,
6
- turbopack: {
7
- root: fileURLToPath(new URL('.', import.meta.url)),
8
- },
9
- };
10
-
11
- export default nextConfig;
1
+ import { fileURLToPath } from 'node:url';
2
+
3
+ /** @type {import('next').NextConfig} */
4
+ const nextConfig = {
5
+ reactCompiler: true,
6
+ turbopack: {
7
+ root: fileURLToPath(new URL('.', import.meta.url)),
8
+ },
9
+ };
10
+
11
+ export default nextConfig;
@@ -0,0 +1,41 @@
1
+ # Projeto de Testes de Integração (E2E) — Cypress
2
+
3
+ Projeto criado com o `create-codeverse`: testes End-to-End com o Cypress. O Cypress abre um site
4
+ de verdade no navegador e interage com ele como um usuário faria.
5
+
6
+ ## Como rodar os testes
7
+
8
+ | Passo | Comando |
9
+ |---|---|
10
+ | Deixar o site a ser testado rodando | por padrão, em [http://localhost:3000](http://localhost:3000) |
11
+ | Abrir o terminal do VS Code | `` Ctrl + ` `` |
12
+ | Abrir o Cypress | `npm test` |
13
+ | No Cypress | Escolha **E2E Testing**, depois um navegador, depois o teste `meu-teste.cy.js` |
14
+
15
+ Para testar outro endereço, troque o `baseUrl` em `cypress.config.js`.
16
+
17
+ ## Scripts
18
+
19
+ | Comando | O que faz |
20
+ |---|---|
21
+ | `npm test` | Abre o Cypress |
22
+ | `npm run clean` | Apaga do PC as versões antigas do programa Cypress (cerca de 200 MB cada), mantendo só a usada neste projeto |
23
+
24
+ ## Estrutura
25
+
26
+ | Pasta / arquivo | Para que serve |
27
+ |---|---|
28
+ | `cypress/e2e/meu-teste.cy.js` | Teste E2E, com um exemplo de cada tipo de verificação |
29
+ | `cypress/fixtures/` | Dados de exemplo para os testes |
30
+ | `cypress/support/` | Arquivos de apoio do Cypress (comandos personalizados) |
31
+ | `cypress.config.js` | Configuração do Cypress (`baseUrl`) |
32
+
33
+ Os seletores e textos de `meu-teste.cy.js` (ex.: `h1`, `'Texto do título'`) são exemplos: ajuste
34
+ para os elementos do site que você está testando.
35
+
36
+ ## Para saber mais
37
+
38
+ | Assunto | Link |
39
+ |---|---|
40
+ | Cypress E2E | [docs.cypress.io](https://docs.cypress.io/app/end-to-end-testing/writing-your-first-end-to-end-test) |
41
+ | Material da CodeVerse | [codeverse.dev.br](https://codeverse.dev.br) |
@@ -32,6 +32,7 @@
32
32
  "node": ">=20"
33
33
  },
34
34
  "scripts": {
35
- "test": "cls && cypress open"
35
+ "test": "cls && cypress open",
36
+ "clean": "cls && npx cypress cache prune && rem Apaga do PC as versões antigas do programa Cypress, cerca de 200 MB cada, e mantém só a usada neste projeto"
36
37
  }
37
38
  }
@@ -0,0 +1,49 @@
1
+ # Projeto de Testes — Jest
2
+
3
+ Projeto criado com o `create-codeverse`: JavaScript (ES Modules) com o Jest, para testes unitários
4
+ (funções, classes e regras de negócio) e testes com dependências (mocks).
5
+
6
+ ## Como rodar os testes
7
+
8
+ | Passo | Comando |
9
+ |---|---|
10
+ | Abrir o terminal do VS Code | `` Ctrl + ` `` |
11
+ | Rodar todos os testes | `npm test` |
12
+ | Gerar o relatório em JSON (com cobertura) | `npm run report` |
13
+ | Gerar e abrir o relatório em HTML | `npm run dashboard` |
14
+
15
+ ## Scripts
16
+
17
+ | Comando | O que faz |
18
+ |---|---|
19
+ | `npm test` | Limpa o terminal e roda todos os testes, um arquivo por vez, mostrando cada caso |
20
+ | `npm run report` | Roda os testes com cobertura e grava `coverage/relatorio.json` |
21
+ | `npm run dashboard` | Gera o relatório em `_html-report/index.html` e abre no navegador |
22
+
23
+ ## Estrutura
24
+
25
+ | Pasta / arquivo | Para que serve |
26
+ |---|---|
27
+ | `src/nome-do-seu-script.js` | Código a ser testado: troque pela sua função ou classe |
28
+ | `tests/nome-do-script.test.js` | Testes, com um exemplo de cada verificação (`toBe`, `toEqual`, `toContain`...) |
29
+ | `jest.reporters.config.mjs` | Configuração do relatório em HTML |
30
+ | `.env.example` | Modelo das variáveis de ambiente: copie para `.env` e preencha |
31
+
32
+ Se você escolheu **Dependências** no `create-codeverse`, o arquivo de testes também traz exemplos
33
+ de mocks com `jest.fn()` (`mockReturnValue`, `mockResolvedValue`, `toHaveBeenCalledWith`...) e o
34
+ projeto já vem com o `axios` instalado.
35
+
36
+ ## Como escrever um teste
37
+
38
+ | Parte | Exemplo | O que faz |
39
+ |---|---|---|
40
+ | `describe` | `describe('soma', () => { ... })` | Agrupa os testes de um assunto |
41
+ | `it` | `it('soma dois números', () => { ... })` | Um caso de teste |
42
+ | `expect` | `expect(soma(1, 2)).toBe(3)` | Confere o resultado |
43
+
44
+ ## Para saber mais
45
+
46
+ | Assunto | Link |
47
+ |---|---|
48
+ | Jest | [jestjs.io/docs](https://jestjs.io/docs/getting-started) |
49
+ | Material da CodeVerse | [codeverse.dev.br](https://codeverse.dev.br) |