Skip to content

Agregando unit test para filter-store-product y cambio en pagination.middleware - #71

Merged
SebaKisser merged 2 commits into
devfrom
OM-424
Mar 30, 2026
Merged

SebaKisser merged 2 commits into
devfrom
OM-424

Conversation

@CrisNAC

@CrisNAC CrisNAC commented Mar 30, 2026 •

Copy link
Copy Markdown
Owner

Summary by CodeRabbit

Notas de Lanzamiento

  • Bug Fixes

    • Se mejoró la validación de parámetros de paginación en la API. Ahora rechaza valores inválidos (no números, negativos o que excedan límites) con un mensaje de error descriptivo (HTTP 400).
  • Tests

    • Se añadieron nuevas pruebas unitarias para validar el comportamiento del filtrado de productos.

@coderabbitai

coderabbitai Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

La PR centraliza constantes de paginación en un nuevo módulo y fortalece el middleware de paginación con validación más rigurosa. Ahora retorna errores HTTP 400 para parámetros inválidos en lugar de aplicar valores por defecto silenciosamente.

Changes

Cohort / File(s) Summary
Constantes y middleware de paginación
src/utils/contants/pagination.contant.js, src/middlewares/pagination.middleware.js
Se agregó un nuevo módulo de constantes con DEFAULT_PAGE: 1, DEFAULT_LIMIT: 20 y MAX_LIMIT: 100. El middleware ahora importa estas constantes y valida que page y limit sean enteros positivos y que limit no exceda MAX_LIMIT, retornando HTTP 400 con detalle de errores cuando la validación falla.
Suite de pruebas para filtrado de productos
tests/unit/commerce/filter-store-product.test.js
Nueva suite de tests que valida el endpoint GET /api/commerces/products/filter/:id con mocks de Prisma. Cubre validación de existencia de comercio, parámetros de filtro (name, category, available, isOffer, rango de precios), opciones de ordenamiento (sortBy, sortOrder), paginación (incluyendo validación del límite máximo de 100) y la estructura esperada de respuesta con campos de paginación y propiedades del producto.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

Suggested reviewers

  • SebaKisser
  • Andoumeda

Poem

🐰 En el módulo de constantes saltamos a crear,
validaciones correctas sin dejar pasar,
página y límite ahora con razón,
cuatrocientos errores por mala intención. ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed El título describe dos cambios principales del PR: la adición de un test unitario para filter-store-product y cambios en pagination.middleware, lo cual se alinea con los archivos modificados.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch OM-424

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 (1)
tests/unit/commerce/filter-store-product.test.js (1)

430-433: Evitá hardcodear 100 en el test de límite.

Conviene leer MAX_LIMIT desde src/utils/contants/pagination.contant.js para no duplicar reglas y evitar drift cuando cambie la constante.

♻️ Refactor sugerido
+import paginationConstants from "../../../src/utils/contants/pagination.contant.js";
+const { MAX_LIMIT } = paginationConstants;

- it("devuelve 400 cuando limit supera 100", async () => {
+ it(`devuelve 400 cuando limit supera ${MAX_LIMIT}`, async () => {
   const res = await request(app).get(
-    "/api/commerces/products/filter/1?limit=200"
+    `/api/commerces/products/filter/1?limit=${MAX_LIMIT + 1}`
   );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/commerce/filter-store-product.test.js` around lines 430 - 433,
Replace the hardcoded 100 in the test "devuelve 400 cuando limit supera 100" by
importing MAX_LIMIT from src/utils/contants/pagination.contant.js and use it to
build the request (e.g., request(...`?limit=${MAX_LIMIT + 1}`)). Update the
assertion/description text if needed to avoid embedding the literal 100 and
ensure the test still expects a 400 when limit > MAX_LIMIT; reference the
constant name MAX_LIMIT and the test case name to locate where to change.
🤖 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/unit/commerce/filter-store-product.test.js`:
- Around line 258-263: Las aserciones actuales buscan b.AND arrays pero el
servicio construye objetos planos en where.OR; actualiza las comprobaciones en
tests/unit/commerce/filter-store-product.test.js para inspeccionar las
propiedades directas de cada rama en where.OR (p. ej. comprobar b.is_offer ===
false && b.price?.gte === 10 en lugar de b.AND?.some(...)) usando la misma
variable where y la extracción prisma.products.findMany.mock.calls[0][0].where;
aplica el mismo cambio a los bloques mencionados (las otras ubicaciones 275-280,
309-317, 329-334, 345-350) ajustando las condiciones para offer_price/price y
los valores esperados según cada caso.

---

Nitpick comments:
In `@tests/unit/commerce/filter-store-product.test.js`:
- Around line 430-433: Replace the hardcoded 100 in the test "devuelve 400
cuando limit supera 100" by importing MAX_LIMIT from
src/utils/contants/pagination.contant.js and use it to build the request (e.g.,
request(...`?limit=${MAX_LIMIT + 1}`)). Update the assertion/description text if
needed to avoid embedding the literal 100 and ensure the test still expects a
400 when limit > MAX_LIMIT; reference the constant name MAX_LIMIT and the test
case name to locate where to change.
🪄 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: ed17e32c-3658-4731-af15-0ab9b7031f84

📥 Commits

Reviewing files that changed from the base of the PR and between dd5b950 and 7045f90.

📒 Files selected for processing (3)
  • src/middlewares/pagination.middleware.js
  • src/utils/contants/pagination.contant.js
  • tests/unit/commerce/filter-store-product.test.js

Comment thread tests/unit/commerce/filter-store-product.test.js
@SebaKisser
SebaKisser merged commit bba1d9d into dev Mar 30, 2026
1 of 3 checks passed
@coderabbitai coderabbitai Bot mentioned this pull request Apr 2, 2026
@Andoumeda
Andoumeda deleted the OM-424 branch April 11, 2026 17:11
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