Skip to content

OM-411: agregue unit tests de funciones de order.service.js - #79

Merged
CrisNAC merged 2 commits into
devfrom
OM-411
Apr 6, 2026
Merged

CrisNAC merged 2 commits into
devfrom
OM-411

Conversation

@leoAchu16

@leoAchu16 leoAchu16 commented Apr 6, 2026 •

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

Notas de Lanzamiento

  • Tests
    • Se han agregado pruebas unitarias extensivas para validar el comportamiento de los servicios de órdenes, asegurando mayor confiabilidad en la gestión de pedidos, estados de envío y validaciones de acceso.

@coderabbitai

coderabbitai Bot commented Apr 6, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Recorrido

Se agregó una nueva suite de pruebas unitarias en Vitest que valida el comportamiento de cuatro servicios relacionados con órdenes: createOrderService, getOrdersService, getStoreOrdersService y updateOrderStatusService. Las pruebas verifican manejo de errores, control de acceso, mapeo de datos y transiciones de estado, incluyendo casos de éxito y casos de error con errores personalizados específicos.

Cambios

Cohort / Archivo(s) Resumen
Suite de pruebas de servicios de órdenes
tests/unit/order/order.test.js
Agregó 610 líneas de pruebas unitarias que validan createOrderService, getOrdersService, getStoreOrdersService y updateOrderStatusService. Cubre creación de órdenes, recuperación con paginación y filtrado, validaciones de permisos por rol (SELLER, DELIVERY, CUSTOMER), transiciones de estado, manejo de errores (NotFoundError, ForbiddenError, ValidationError, ConflictError) y cálculos de precios con historial de ofertas.

Esfuerzo estimado de revisión de código

🎯 2 (Simple) | ⏱️ ~10 minutos

PRs posiblemente relacionados

  • OM-412 #60: Las nuevas pruebas unitarias validan directamente el comportamiento de las mismas funciones de servicios de órdenes que fueron agregadas/modificadas en ese PR.
  • fix: ajustes menores en order service #68: Las pruebas verifican comportamientos de getStoreOrdersService y updateOrderStatusService (parseo de filtros de estado y reglas de transición) que corresponden directamente a los cambios de código en ese PR.
  • OM-412: ahora se puede enviar el address como null en createOrder #76: Las pruebas validan comportamiento de createOrderService cuando addressId es nulo, lo que corresponde a cambios que hicieron la dirección opcional en ese PR.

Revisores sugeridos

  • CrisNAC

Poema

🐰 Hola, amigos del código, qué alegría ver
Nuevas pruebas de órdenes para validar bien,
Mocks y casos de error, transiciones de estado,
Un test bien estructurado, ¡perfectamente escalado! ✨

🚥 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 correctamente el cambio principal: agregar pruebas unitarias para funciones del archivo order.service.js, lo cual coincide exactamente con el contenido del PR que añade 610 líneas de tests.
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-411

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.

🧹 Nitpick comments (1)
tests/unit/order/order.test.js (1)

364-394: Las aserciones de filtros son débiles y no verifican el comportamiento real.

Los tests para order_status, múltiples estados y rango de fechas solo verifican que $transaction fue llamado, pero no comprueban que los filtros se apliquen correctamente. Esto significa que si la lógica de filtrado estuviera rota, los tests seguirían pasando.

Considerar inspeccionar los argumentos pasados a las queries dentro de la transacción para verificar que los filtros order_status y date_from/date_to se construyan correctamente.

♻️ Ejemplo de aserción más robusta para el filtro de status
  it("aplica filtro por order_status correctamente", async () => {
    prisma.stores.findFirst.mockResolvedValue({ id_store: 10 });
-   prisma.$transaction.mockResolvedValue([[mockOrderFromDB], 1]);
+   prisma.$transaction.mockImplementation(async (queries) => {
+     // Capturar y verificar los argumentos de las queries
+     return [[mockOrderFromDB], 1];
+   });

    await getStoreOrdersService(1, 10, { order_status: "PENDING" });

-   const [findManyCall] = prisma.$transaction.mock.calls[0][0];
-   // verificamos que la transacción fue llamada
-   expect(prisma.$transaction).toHaveBeenCalled();
+   expect(prisma.$transaction).toHaveBeenCalled();
+   // TODO: Verificar que el where clause incluye { order_status: "PENDING" }
  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/unit/order/order.test.js` around lines 364 - 394, The tests for
getStoreOrdersService currently only assert prisma.$transaction was called;
update each test to inspect the actual query arguments passed into
prisma.$transaction (mock.calls[0][0]) and assert the generated Prisma where
clauses include the expected filters: for order_status verify the where includes
a condition on order_status (or an OR/IN array) matching "PENDING" or
["PENDING","PROCESSING"], and for date_from/date_to verify the where contains
created_at (or the appropriate date field) with gte/lte bounds for "2026-01-01"
and "2026-12-31"; locate the calls via getStoreOrdersService and
prisma.$transaction to make these assertions instead of only checking that the
transaction was invoked.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/unit/order/order.test.js`:
- Around line 364-394: The tests for getStoreOrdersService currently only assert
prisma.$transaction was called; update each test to inspect the actual query
arguments passed into prisma.$transaction (mock.calls[0][0]) and assert the
generated Prisma where clauses include the expected filters: for order_status
verify the where includes a condition on order_status (or an OR/IN array)
matching "PENDING" or ["PENDING","PROCESSING"], and for date_from/date_to verify
the where contains created_at (or the appropriate date field) with gte/lte
bounds for "2026-01-01" and "2026-12-31"; locate the calls via
getStoreOrdersService and prisma.$transaction to make these assertions instead
of only checking that the transaction was invoked.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: be8aa19b-4ea2-4e9b-b64b-5b4d9d00aff4

📥 Commits

Reviewing files that changed from the base of the PR and between 179019d and cb303db.

📒 Files selected for processing (1)
  • tests/unit/order/order.test.js

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