Skip to content

Om 432 - #78

Merged
J-Kanami-PS merged 9 commits into
devfrom
OM-432
Apr 6, 2026
Merged

J-Kanami-PS merged 9 commits into
devfrom
OM-432

Conversation

@SebaKisser

@SebaKisser SebaKisser commented Apr 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Notas de Lanzamiento

  • Bug Fixes

    • Corrección ortográfica en mensaje de error de contraseña.
  • Tests

    • Consultas de productos con parámetros inválidos ahora responden 400 con errores.
    • Pruebas de comercios incluyen geocodificación (lat/lon) y mock de geocoding externo.
    • Suite de etiquetas ahora valida respuesta exitosa, filtrado y límite.
    • Mayor robustez en pruebas de usuarios y direcciones; mocks reset más agresivo.
  • Chores

    • Mejoras en configuración de pruebas CI: nuevos scripts de test y carga de variables de entorno.

@coderabbitai

coderabbitai Bot commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@SebaKisser has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 32 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 0 minutes and 32 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 81bfc1ca-53db-415b-bb4a-9aab4aa22b61

📥 Commits

Reviewing files that changed from the base of the PR and between cc0f5cb and eed7d22.

📒 Files selected for processing (2)
  • .github/workflows/vitest-supertest.yml
  • tests/e2e/stores.test.js
📝 Walkthrough

Walkthrough

Se añadieron/ajustaron variables de entorno en el workflow de tests, se cargó dotenv en el cliente Prisma, se corrigió una tilde en un mensaje de servicio y se remodelaron múltiples suites e2e (mocks, aserciones y cuerpos de petición). También se agregaron scripts npm para testeo más granular.

Changes

Cohort / File(s) Summary
Workflow de CI
\.github/workflows/vitest-supertest.yml
Se amplió el bloque env para pruebas (nuevas vars: DATABASE_URL_TEST, DIRECT_URL_TEST, NODE_ENV: test, y varios ${{ secrets.* }}); comando activo sigue npm run test:run; se añadió npm run test:ci comentado.
Prisma / Entorno
src/lib/prisma.js
Se importó dotenv/config al inicio del módulo para cargar variables de entorno desde .env.
Mensajes de Servicio
src/modules/users/users/services/users.services.js
Corrección tipográfica: “La contrasena actual es incorrecta” → “La contraseña actual es incorrecta” en updateUserPasswordService.
Scripts de NPM
package.json
Se agregaron test:unit (vitest run tests/unit) y test:ci (vitest run --exclude tests/e2e/product/filter-product.test.js).
Tests — Productos
tests/e2e/product/products.test.js
Se ajustó expectativa para page/limit inválidos: ahora espera HTTP 400 y respuesta con errors.
Tests — Tags
tests/e2e/tags.test.js
Suite reescrita para validar éxito del endpoint: mock de prisma.productTags.findMany, comprobaciones de esquema, search y limit, y casos con/ sin resultados.
Tests — Tiendas
tests/e2e/stores.test.js
beforeEach modificado para stubar global.fetch con { ok: true, json: async ()=>({ address: {} }) }; payloads de POST /api/commerces extendidos con latitude y longitude.
Tests — Usuarios
tests/e2e/users.test.js
Mocks de Prisma ampliados (addresses.findUnique, addresses.updateMany), vi.clearAllMocks() → vi.resetAllMocks(), remodelado prisma.users.findUnique y ajustes en pruebas de actualización de direcciones (cuerpos y mocks).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • CrisNAC
  • Andoumeda
  • leoAchu16

Poem

🐰
Brinco entre mocks y tests con afán,
una tilde vuelve a su lugar,
dotenv prende el farol en mi madriguera,
los endpoints bailan, la suite va a pasar,
¡y yo me zampo una zanahoria al compás! 🥕✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive El título 'Om 432' es vago y genérico, no describe claramente el cambio principal del PR. No comunica qué se modificó o cuál es el objetivo. Reemplazar el título con una descripción clara del cambio principal, por ejemplo: 'Mejorar configuración de tests e2e y corregir validaciones de endpoints' o similar que refleje los cambios realizados.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-432

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
tests/e2e/tags.test.js (1)

60-69: Este caso no prueba realmente el filtro search.

Como findMany ya está mockeado con el resultado filtrado, el test sigue pasando aunque el service ignore req.query.search. Conviene afirmar también la query enviada a Prisma.

💡 Ajuste sugerido
   const res = await request(app).get("/products/tags?search=oferta");

   expect(res.status).toBe(200);
   expect(res.body).toHaveLength(1);
   expect(res.body[0].name).toBe("Oferta");
+  expect(prisma.productTags.findMany).toHaveBeenCalledWith(
+    expect.objectContaining({
+      where: expect.objectContaining({
+        name: expect.objectContaining({
+          contains: "oferta",
+          mode: "insensitive",
+        }),
+      }),
+    })
+  );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/e2e/tags.test.js` around lines 60 - 69, The test currently mocks
prisma.productTags.findMany to return a filtered array so it doesn't verify that
the controller/service actually applied the search filter; update the test to
also assert the call to prisma.productTags.findMany contains the expected query
object (e.g. check prisma.productTags.findMany was called with an
objectContaining where.name contains the search term "oferta" with appropriate
case/insensitive options) after making the GET request to
"/products/tags?search=oferta" so the test fails if the service ignores
req.query.search.
tests/e2e/product/products.test.js (1)

153-160: Hacé este 400 más específico.

Con el assert actual, el caso pasa con cualquier respuesta que tenga errors, aunque no marque ambos parámetros inválidos. Ya que este camino debería cortar antes de pegarle a Prisma, también conviene afirmarlo.

💡 Ajuste sugerido
   const res = await request(app).get("/products?page=-1&limit=0");

   expect(res.status).toBe(400);
-  expect(res.body).toHaveProperty("errors");
+  expect(res.body.errors).toEqual(
+    expect.arrayContaining([
+      expect.objectContaining({ field: "page" }),
+      expect.objectContaining({ field: "limit" }),
+    ])
+  );
+  expect(prisma.products.count).not.toHaveBeenCalled();
+  expect(prisma.products.findMany).not.toHaveBeenCalled();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/e2e/product/products.test.js` around lines 153 - 160, Tighten the test
"Error 400 cuando los parametros son invalidos": assert that the response errors
specifically mention both invalid "page" and "limit" parameters (instead of just
checking existence of errors) and also assert that prisma.products.count and
prisma.products.findMany were not called to ensure validation short-circuits
before DB access; locate the test's
request(app).get("/products?page=-1&limit=0") call and replace the generic
expect(res.body).toHaveProperty("errors") with checks for the expected error
messages and expect(prisma.products.count).not.toHaveBeenCalled() and
expect(prisma.products.findMany).not.toHaveBeenCalled().
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/e2e/stores.test.js`:
- Around line 225-231: El stub global de fetch se crea en beforeEach usando
vi.stubGlobal("fetch", ...) y no se restaura, lo que puede filtrar a otros
tests; añade un afterEach que invoque vi.unstubAllGlobals() para limpiar los
stubs globales (restaurando fetch) al finalizar cada test, manteniendo la
configuración actual de beforeEach con vi.resetAllMocks().

---

Nitpick comments:
In `@tests/e2e/product/products.test.js`:
- Around line 153-160: Tighten the test "Error 400 cuando los parametros son
invalidos": assert that the response errors specifically mention both invalid
"page" and "limit" parameters (instead of just checking existence of errors) and
also assert that prisma.products.count and prisma.products.findMany were not
called to ensure validation short-circuits before DB access; locate the test's
request(app).get("/products?page=-1&limit=0") call and replace the generic
expect(res.body).toHaveProperty("errors") with checks for the expected error
messages and expect(prisma.products.count).not.toHaveBeenCalled() and
expect(prisma.products.findMany).not.toHaveBeenCalled().

In `@tests/e2e/tags.test.js`:
- Around line 60-69: The test currently mocks prisma.productTags.findMany to
return a filtered array so it doesn't verify that the controller/service
actually applied the search filter; update the test to also assert the call to
prisma.productTags.findMany contains the expected query object (e.g. check
prisma.productTags.findMany was called with an objectContaining where.name
contains the search term "oferta" with appropriate case/insensitive options)
after making the GET request to "/products/tags?search=oferta" so the test fails
if the service ignores req.query.search.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 143d946b-7e44-4b9d-b3fc-22eee3d19d16

📥 Commits

Reviewing files that changed from the base of the PR and between 3f06fa7 and 2b0fe65.

📒 Files selected for processing (6)
  • .github/workflows/vitest-supertest.yml
  • src/modules/users/users/services/users.services.js
  • tests/e2e/product/products.test.js
  • tests/e2e/stores.test.js
  • tests/e2e/tags.test.js
  • tests/e2e/users.test.js

Comment thread tests/e2e/stores.test.js

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
package.json (1)

12-12: Evitá depender de exclusión por path fijo en CI.

En Line 12, excluir un archivo puntual puede ocultar regresiones si ese script se activa en pipeline. Conviene mover esta excepción a una config de CI dedicada y dejar trazabilidad (issue/link + fecha objetivo de remoción).

Propuesta concreta
-    "test:ci": "vitest run --exclude tests/e2e/product/filter-product.test.js",
+    "test:ci": "vitest run -c vitest.config.ci.js",
// vitest.config.ci.js (nuevo)
import base from "./vitest.config.js";
import { defineConfig, mergeConfig } from "vitest/config";

export default mergeConfig(
  base,
  defineConfig({
    test: {
      exclude: ["tests/e2e/product/filter-product.test.js"] // TODO: remover cuando se resuelva ISSUE-XXX
    }
  })
);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@package.json` at line 12, La línea "test:ci" en package.json no debe depender
de una exclusión por path fijo; quita la opción --exclude de la entrada
"test:ci" y en su lugar crea un nuevo archivo de configuración
vitest.config.ci.js que importe/mergue vitest.config.js y ponga la exclusión
("tests/e2e/product/filter-product.test.js") en test.exclude con un comentario
TODO con el número de issue/link y fecha objetivo de eliminación; luego
actualiza "test:ci" para usar esa config CI (ej. --config vitest.config.ci.js).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/vitest-supertest.yml:
- Around line 28-29: Remueve las credenciales embebidas en las variables
DATABASE_URL y DIRECT_URL y sustitúyelas por referencias a secretos/variables de
entorno administradas (por ejemplo usar secrets como TEST_DATABASE_URL y
TEST_DIRECT_URL o variables de entorno del runner) en la configuración del
workflow; actualiza la configuración del repositorio/CI para añadir esos
secretos y asegúrate de que cualquier servicio de base de datos de prueba (p.
ej. el servicio Docker/postgres usado en la job) acepte la URL desde esas
variables en lugar de valores en texto plano.

---

Nitpick comments:
In `@package.json`:
- Line 12: La línea "test:ci" en package.json no debe depender de una exclusión
por path fijo; quita la opción --exclude de la entrada "test:ci" y en su lugar
crea un nuevo archivo de configuración vitest.config.ci.js que importe/mergue
vitest.config.js y ponga la exclusión
("tests/e2e/product/filter-product.test.js") en test.exclude con un comentario
TODO con el número de issue/link y fecha objetivo de eliminación; luego
actualiza "test:ci" para usar esa config CI (ej. --config vitest.config.ci.js).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 33b1037e-7074-4b02-8256-54fdeaa9cb85

📥 Commits

Reviewing files that changed from the base of the PR and between 2b0fe65 and a5c222c.

📒 Files selected for processing (3)
  • .github/workflows/vitest-supertest.yml
  • package.json
  • src/lib/prisma.js
✅ Files skipped from review due to trivial changes (1)
  • src/lib/prisma.js

Comment thread .github/workflows/vitest-supertest.yml Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/vitest-supertest.yml:
- Around line 55-59: The workflow currently runs the unstable e2e suite via the
"npm run test:run" step despite the note about a failing file; change the CI
step to run the deterministic suite by replacing or uncommenting the "npm run
test:ci" invocation and remove or update the comment that says one file fails so
it no longer executes the unstable "test:run"; target the lines that reference
the run commands "npm run test:run" and "npm run test:ci" in the
vitest-supertest.yml and ensure only "npm run test:ci" runs for PRs.
- Around line 31-32: The CI workflow is exporting DATABASE_URL from secrets so
the test job (which runs "npx prisma db push") can hit the production DB; change
the workflow to set DATABASE_URL to the test secret (use DATABASE_URL_TEST) for
the vitest-supertest job or ensure the job exports DATABASE_URL_TEST and the
test step sets DATABASE_URL=$DATABASE_URL_TEST before running migrations;
additionally consider updating src/lib/prisma.js to select
process.env.DATABASE_URL_TEST when NODE_ENV==='test' (instead of always reading
process.env.DATABASE_URL) so "npx prisma db push" and Prisma client
instantiation use the test DB during tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b91bc6e8-eabf-4865-ab38-71b31f3eee25

📥 Commits

Reviewing files that changed from the base of the PR and between a5c222c and cc0f5cb.

📒 Files selected for processing (1)
  • .github/workflows/vitest-supertest.yml

Comment thread .github/workflows/vitest-supertest.yml
Comment thread .github/workflows/vitest-supertest.yml Outdated
@J-Kanami-PS
J-Kanami-PS merged commit f9fb29b into dev Apr 6, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants