Skip to content

test(backend): add comprehensive unit and integration tests across all features#27

Closed
tahiry-dev-29 wants to merge 0 commit into
mainfrom
feat/backend-tests
Closed

test(backend): add comprehensive unit and integration tests across all features#27
tahiry-dev-29 wants to merge 0 commit into
mainfrom
feat/backend-tests

Conversation

@tahiry-dev-29

@tahiry-dev-29 tahiry-dev-29 commented Jul 22, 2026

Copy link
Copy Markdown
Owner

Summary

Adds ~50 new test spec files (+5,417 lines) covering unit and integration tests across all backend feature domains, plus vitest configuration, source fixes uncovered during testing, and supporting setup.


Changes

New Test Suites

Domain Files Type
Health health.controller.spec.ts Integration
Auth (Core) auth-guards, store-branch-scope.guard, auth-integration, auth-credentials, auth-audit, auth-mail, auth-oauth, auth-recovery, auth-token-security, password-security, trusted-device, two-factor Unit + Integration
Analytics analytics.repository, analytics.resolver.integration, analytics.service Unit + Integration
Employee employee-role-assignment.service, role-permission.service, role.service Unit
Messaging email.processor, messaging-resolvers.integration, email-template.service, messaging.service Unit + Integration
Notifications notification-resolver.integration, notification-transport.service, notification.service, push-notification.service, notification-queue.service, sms-notification.service Unit + Integration
Settings currency.service, language.service, settings-resolvers.integration, setting.service Unit + Integration
Social Media facebook.service, instagram.service, social-media.processor, social-media.resolver.integration, social-media.service Unit + Integration
Support live-chat.gateway, support-ticket.resolver.integration, support-ticket.service Unit + Integration

Config & Setup

  • Vitest configs added for: apps/api, auth (core), analytics, employee, messaging, notifications, settings, social-media, support
  • Root vitest.config.ts updated to pick up API app vitest config
  • ESLint rules relaxed for test files (max-lines, no-explicit-any)
  • .swcrc config added; migrated to @nx/vitest plugin and vite-plugin-static-copy / vite-tsconfig-paths

Source Fixes

File Fix
auth/src/index.ts Use export type for JwtPayload
auth/current-user.decorator.ts Use import type / export type for AuthUser
auth/vitest.config.ts Add tsconfigPaths + meilisearch alias
customer/src/index.ts Export missing resolvers (auth, magic-link, oauth)
employee/src/index.ts Export missing resolvers/services (role, permission, assignment)
notification-transport.service.ts Add missing this.events$.next(event) in publish()
support-ticket.formatter.ts Add customerId / employeeId to formatted output

Housekeeping

  • Todo files consolidated: 14 files → 6 structured markdown files
  • 01-backend.md updated with completed test checklist items

Test Plan

  • All unit tests pass in isolation
  • Integration tests verified against mock services
  • No breaking changes to existing APIs or resolvers

Summary by CodeRabbit

  • Bug Fixes

    • Notifications now appear immediately for active real-time subscribers, without waiting for synchronization.
    • Support ticket responses now consistently include customer and employee identifiers where applicable.
  • Tests

    • Added comprehensive automated coverage for authentication, permissions, health checks, analytics, messaging, notifications, settings, social media, support, and employee management.
    • Expanded validation for login security, role-based access, ticket ownership, notification delivery, and scheduled processing.
  • Documentation

    • Marked backend testing checklist items as complete.

@tahiry-dev-29 tahiry-dev-29 self-assigned this Jul 22, 2026
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds Vitest configurations and extensive backend unit/integration tests across authentication, RBAC, settings, analytics, notifications, messaging, social media, support, and health. It also updates test linting, project discovery, public exports, notification transport behavior, formatter output, TypeScript configs, and backend testing checklists.

Changes

Backend test infrastructure

Layer / File(s) Summary
Test runner, linting, and project wiring
.eslintrc.json, eslint.config.mjs, vitest.config.ts, apps/*/vitest.config.ts, libs/backend/**/vitest.config.ts, libs/backend/features/{employee,messaging}/tsconfig*.json
Adds Vitest project discovery and per-project Node configurations, relaxes selected test lint rules, and adds TypeScript project settings.
Public exports and type-only imports
libs/backend/core/auth/src/index.ts, libs/backend/core/auth/src/lib/decorators/current-user.decorator.ts, libs/backend/features/{customer,employee}/src/index.ts
Changes authentication model exports to type-only and expands customer and employee feature barrel exports.

Authentication and authorization

Layer / File(s) Summary
Health and authentication flows
apps/api/src/health/health.controller.spec.ts, libs/backend/core/auth/src/lib/services/*spec.ts
Tests health success/failure responses, credentials, audit logging, OAuth, recovery, mail, token security, password security, trusted devices, and two-factor behavior.
Guards and scope enforcement
libs/backend/core/auth/src/lib/guards/*spec.ts
Tests GraphQL request extraction, customer/employee access, super-admin and optional access, permissions, and store-branch scope checks.

Employee RBAC

Layer / File(s) Summary
Roles, permissions, and assignments
libs/backend/features/employee/src/lib/{role,role-permission,employee-role-assignment}.service.spec.ts
Tests role lifecycle rules, permission aggregation and cache invalidation, employee role assignments, temporary elevations, and branch assignments.

Analytics and settings

Layer / File(s) Summary
Analytics services and resolvers
libs/backend/features/analytics/src/lib/*spec.ts
Tests dashboard queries, product rankings, view tracking and IP anonymization, repository writes, and resolver request forwarding.
Settings services and resolvers
libs/backend/features/settings/src/lib/**/*spec.ts
Tests setting parsing and persistence, language and currency defaults, exchange-rate synchronization, resolver operations, and public-settings cache behavior.

Messaging and notifications

Layer / File(s) Summary
Messaging and email processing
libs/backend/features/messaging/src/lib/**/*spec.ts
Tests messaging threads, replies, inbox retrieval, email templates, resolver delegation, and queued email success/failure handling.
Notification delivery and transport
libs/backend/features/notifications/src/lib/**/*spec.ts, libs/backend/features/notifications/src/lib/notification-transport.service.ts
Tests notification creation, preferences, read state, subscriptions, push/SMS paths, queue dispatch, resolver/SSE behavior, and adds immediate in-memory event emission during publishing.

Social media and support

Layer / File(s) Summary
Social publishing
libs/backend/features/social-media/src/lib/**/*spec.ts
Tests Facebook and Instagram integrations, immediate and scheduled publishing, queue processing, error status updates, and resolver delegation.
Support tickets and live chat
libs/backend/features/support/src/lib/**/*spec.ts
Tests WebSocket chat flows, ticket creation/replies/assignment, resolver argument propagation, and formatter identity fields.

Backend checklist

Layer / File(s) Summary
Completed backend test scenarios
todos/01-backend.md
Marks the listed authentication, RBAC, settings, health, notifications, support, messaging, analytics, and social-media test scenarios as completed.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

  • tahiry-dev-29/Swift-Shop#15: Adds related Vitest coverage for the social-media services, processors, resolvers, and Prisma integration.

Suggested labels: enhancement

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the PR’s main change: adding comprehensive backend unit and integration tests across many features.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ 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 feat/backend-tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Checkov (3.3.8)
.eslintrc.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'

libs/backend/features/employee/tsconfig.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'

libs/backend/features/employee/tsconfig.lib.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'

  • 2 others
🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Nitpick comments (3)
libs/backend/features/settings/src/lib/currency.service.spec.ts (1)

81-96: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tighten syncExchangeRates assertion to verify unchanged currencies are skipped.

The test only confirms USD's rate update was called; it doesn't prove EUR (unchanged rate) was not updated, so a regression that updates every currency regardless of change would still pass this test.

♻️ Proposed tightening
       expect(prismaMock.currency.update).toHaveBeenCalledWith({
         where: { id: 'c2' },
         data: { exchangeRate: 1.1 },
       });
+      expect(prismaMock.currency.update).not.toHaveBeenCalledWith(
+        expect.objectContaining({ where: { id: 'c1' } }),
+      );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/backend/features/settings/src/lib/currency.service.spec.ts` around lines
81 - 96, Update the syncExchangeRates test to assert that
prismaMock.currency.update is called only for the changed USD currency and not
for unchanged EUR, while preserving the existing expected USD update
verification.
libs/backend/features/employee/src/lib/role.service.spec.ts (1)

129-290: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: mock return-value slugs are inconsistent with the asserted slugification. The create/cloneRole calls are asserted with underscore slugs (order_specialist, cloned_role), while the corresponding mockResolvedValue returns hyphenated slugs (order-specialist, cloned-role). It's harmless today since only name/id are asserted, but aligning the mock data avoids future confusion.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/backend/features/employee/src/lib/role.service.spec.ts` around lines 129
- 290, Align the mock return values in the create and cloneRole tests with their
asserted slugification by changing the returned slugs to the underscore forms
order_specialist and cloned_role. Update only the mock data in the corresponding
mockResolvedValue calls; keep the existing assertions and test behavior
unchanged.
libs/backend/core/auth/src/lib/services/auth-credentials.service.spec.ts (1)

98-120: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Threshold value is hardcoded implicitly. Seeding failedLoginAttempts: 4 and expecting the update-to-5 to trigger lockout couples this test to LOCKOUT_THRESHOLD === 5. If the constant changes, the initial not-locked guard (failedLoginAttempts >= LOCKOUT_THRESHOLD) or the lockout branch may no longer behave as assumed and the test can silently pass without exercising the lockout path. Consider deriving the seed from the imported LOCKOUT_THRESHOLD constant (e.g. LOCKOUT_THRESHOLD - 1).

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/backend/core/auth/src/lib/services/auth-credentials.service.spec.ts`
around lines 98 - 120, Update the test case around validateCustomer to derive
the initial failedLoginAttempts value from the imported LOCKOUT_THRESHOLD
constant, using one less than the threshold so the failed attempt reliably
exercises the lockout branch. Keep the existing assertions and mock behavior
unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/api/vitest.config.ts`:
- Around line 10-11: Remove the passWithNoTests setting from the Vitest
configurations in apps/api/vitest.config.ts,
libs/backend/features/messaging/vitest.config.ts,
libs/backend/features/notifications/vitest.config.ts,
libs/backend/features/settings/vitest.config.ts, and
libs/backend/features/social-media/vitest.config.ts, leaving each include
pattern unchanged so zero matched specs fail fast.

In `@libs/backend/features/analytics/vitest.config.ts`:
- Around line 7-11: Prevent zero-test Vitest projects from passing by removing
passWithNoTests or explicitly setting it to false in the test configuration at
libs/backend/features/analytics/vitest.config.ts lines 7-11 and
libs/backend/features/employee/vitest.config.ts lines 7-11.

In
`@libs/backend/features/employee/src/lib/employee-role-assignment.service.spec.ts`:
- Around line 116-127: Correct the TemporaryRoleElevation test call to
grantTemporaryRoleElevation by passing a single role ID string and all required
positional arguments, including actorId and reason, matching the valid
invocation later in the suite. Remove the unsafe pastDate cast and pass the Date
value using the method’s actual parameter type.

In
`@libs/backend/features/notifications/src/lib/notification-transport.service.ts`:
- Line 71: Update the notification flow around the service’s publish method and
events$ subscription so Redis-published events are emitted to events$ only once.
Remove the direct emission or prevent the subClient Redis callback from
re-emitting events originating from publish(), while preserving delivery for
externally published notifications.

In `@libs/backend/features/support/src/lib/live-chat.gateway.spec.ts`:
- Around line 66-85: Update the joinChat test and implementation contract so the
customer identity comes from the authenticated socket context rather than the
request payload. In joinChat, derive the verified customerId from the socket
authentication data or reject when the payload customerId does not match before
calling liveChatSession.create; update the test setup and assertions to cover
this authenticated identity.

In `@vitest.config.ts`:
- Line 7: Update the CI Vitest command to include the apps/api project so
apps/api/vitest.config.ts and health.controller.spec.ts are executed; either add
apps/api to the existing path arguments or remove the restrictive libs/backend
filter.

---

Nitpick comments:
In `@libs/backend/core/auth/src/lib/services/auth-credentials.service.spec.ts`:
- Around line 98-120: Update the test case around validateCustomer to derive the
initial failedLoginAttempts value from the imported LOCKOUT_THRESHOLD constant,
using one less than the threshold so the failed attempt reliably exercises the
lockout branch. Keep the existing assertions and mock behavior unchanged.

In `@libs/backend/features/employee/src/lib/role.service.spec.ts`:
- Around line 129-290: Align the mock return values in the create and cloneRole
tests with their asserted slugification by changing the returned slugs to the
underscore forms order_specialist and cloned_role. Update only the mock data in
the corresponding mockResolvedValue calls; keep the existing assertions and test
behavior unchanged.

In `@libs/backend/features/settings/src/lib/currency.service.spec.ts`:
- Around line 81-96: Update the syncExchangeRates test to assert that
prismaMock.currency.update is called only for the changed USD currency and not
for unchanged EUR, while preserving the existing expected USD update
verification.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 614ce497-2605-4803-9945-7a4fa5e63f69

📥 Commits

Reviewing files that changed from the base of the PR and between 4951134 and 49abe59.

📒 Files selected for processing (64)
  • .eslintrc.json
  • apps/api/src/health/health.controller.spec.ts
  • apps/api/vitest.config.ts
  • eslint.config.mjs
  • libs/backend/core/auth/src/index.ts
  • libs/backend/core/auth/src/lib/decorators/current-user.decorator.ts
  • libs/backend/core/auth/src/lib/guards/auth-guards.spec.ts
  • libs/backend/core/auth/src/lib/guards/store-branch-scope.guard.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-audit.service.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-credentials.service.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-integration.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-mail.service.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-oauth.service.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-recovery.service.spec.ts
  • libs/backend/core/auth/src/lib/services/auth-token-security.spec.ts
  • libs/backend/core/auth/src/lib/services/password-security.service.spec.ts
  • libs/backend/core/auth/src/lib/services/trusted-device.service.spec.ts
  • libs/backend/core/auth/src/lib/services/two-factor.service.spec.ts
  • libs/backend/core/auth/vitest.config.ts
  • libs/backend/features/analytics/src/lib/analytics.repository.spec.ts
  • libs/backend/features/analytics/src/lib/analytics.resolver.integration.spec.ts
  • libs/backend/features/analytics/src/lib/analytics.service.spec.ts
  • libs/backend/features/analytics/vitest.config.ts
  • libs/backend/features/customer/src/index.ts
  • libs/backend/features/employee/src/index.ts
  • libs/backend/features/employee/src/lib/employee-role-assignment.service.spec.ts
  • libs/backend/features/employee/src/lib/role-permission.service.spec.ts
  • libs/backend/features/employee/src/lib/role.service.spec.ts
  • libs/backend/features/employee/tsconfig.json
  • libs/backend/features/employee/tsconfig.lib.json
  • libs/backend/features/employee/vitest.config.ts
  • libs/backend/features/messaging/src/lib/processors/email.processor.spec.ts
  • libs/backend/features/messaging/src/lib/resolvers/messaging-resolvers.integration.spec.ts
  • libs/backend/features/messaging/src/lib/services/email-template.service.spec.ts
  • libs/backend/features/messaging/src/lib/services/messaging.service.spec.ts
  • libs/backend/features/messaging/tsconfig.json
  • libs/backend/features/messaging/tsconfig.lib.json
  • libs/backend/features/messaging/vitest.config.ts
  • libs/backend/features/notifications/src/lib/notification-resolver.integration.spec.ts
  • libs/backend/features/notifications/src/lib/notification-transport.service.spec.ts
  • libs/backend/features/notifications/src/lib/notification-transport.service.ts
  • libs/backend/features/notifications/src/lib/notification.service.spec.ts
  • libs/backend/features/notifications/src/lib/push-notification.service.spec.ts
  • libs/backend/features/notifications/src/lib/queue/notification-queue.service.spec.ts
  • libs/backend/features/notifications/src/lib/sms-notification.service.spec.ts
  • libs/backend/features/notifications/vitest.config.ts
  • libs/backend/features/settings/src/lib/currency.service.spec.ts
  • libs/backend/features/settings/src/lib/language.service.spec.ts
  • libs/backend/features/settings/src/lib/resolvers/settings-resolvers.integration.spec.ts
  • libs/backend/features/settings/src/lib/setting.service.spec.ts
  • libs/backend/features/settings/vitest.config.ts
  • libs/backend/features/social-media/src/lib/integrations/facebook.service.spec.ts
  • libs/backend/features/social-media/src/lib/integrations/instagram.service.spec.ts
  • libs/backend/features/social-media/src/lib/social-media.processor.spec.ts
  • libs/backend/features/social-media/src/lib/social-media.resolver.integration.spec.ts
  • libs/backend/features/social-media/src/lib/social-media.service.spec.ts
  • libs/backend/features/social-media/vitest.config.ts
  • libs/backend/features/support/src/lib/live-chat.gateway.spec.ts
  • libs/backend/features/support/src/lib/support-ticket.formatter.ts
  • libs/backend/features/support/src/lib/support-ticket.resolver.integration.spec.ts
  • libs/backend/features/support/src/lib/support-ticket.service.spec.ts
  • libs/backend/features/support/vitest.config.ts
  • todos/01-backend.md
  • vitest.config.ts

Comment thread apps/api/vitest.config.ts Outdated
Comment on lines +10 to +11
include: ['src/**/*.spec.ts'],
passWithNoTests: true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## vitest configs\n'
for f in apps/api/vitest.config.ts \
         libs/backend/features/messaging/vitest.config.ts \
         libs/backend/features/notifications/vitest.config.ts \
         libs/backend/features/settings/vitest.config.ts \
         libs/backend/features/social-media/vitest.config.ts
do
  echo "--- $f"
  cat -n "$f"
done

printf '\n## workspace/package scripts mentioning vitest\n'
rg -n '"(test|vitest)[^"]*"\s*:' -g 'package.json' -g 'pnpm-workspace.yaml' -g 'nx.json' -g 'turbo.json' -g '.github/**' .

printf '\n## matching spec files per project\n'
python3 - <<'PY'
from pathlib import Path
projects = {
    'apps/api': 'apps/api/src/**/*.spec.ts',
    'libs/backend/features/messaging': 'libs/backend/features/messaging/src/**/*.spec.ts',
    'libs/backend/features/notifications': 'libs/backend/features/notifications/src/**/*.spec.ts',
    'libs/backend/features/settings': 'libs/backend/features/settings/src/**/*.spec.ts',
    'libs/backend/features/social-media': 'libs/backend/features/social-media/src/**/*.spec.ts',
}
for root, glob in projects.items():
    base = Path(root)
    files = sorted(base.glob('src/**/*.spec.ts'))
    print(root, len(files))
    for p in files[:20]:
        print('  ', p.as_posix())
PY

Repository: tahiry-dev-29/Swift-Shop

Length of output: 4815


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## vitest config references\n'
rg -n "vitest\.config\.ts|passWithNoTests|include: \['src/\*\*/\*.spec\.ts'\]" apps libs -g 'project.json' -g 'package.json' -g 'vite.config.*' -g 'vitest.config.*' -g 'nx.json'

printf '\n## project test target configs\n'
for f in $(git ls-files 'apps/**/project.json' 'libs/**/project.json'); do
  if rg -q '"test"' "$f"; then
    echo "--- $f"
    cat -n "$f" | sed -n '1,220p'
  fi
done

printf '\n## root vitest config files\n'
git ls-files '*vitest.config.*' '*vite.config.*'

Repository: tahiry-dev-29/Swift-Shop

Length of output: 13034


Fail on zero matched specs
passWithNoTests: true lets these Vitest projects pass even when the glob stops matching or suites are deleted, so CI can go green without running any tests. Remove it from the five configs so missing discovery fails fast.

📍 Affects 5 files
  • apps/api/vitest.config.ts#L10-L11 (this comment)
  • libs/backend/features/messaging/vitest.config.ts#L10-L11
  • libs/backend/features/notifications/vitest.config.ts#L10-L11
  • libs/backend/features/settings/vitest.config.ts#L10-L11
  • libs/backend/features/social-media/vitest.config.ts#L10-L11
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@apps/api/vitest.config.ts` around lines 10 - 11, Remove the passWithNoTests
setting from the Vitest configurations in apps/api/vitest.config.ts,
libs/backend/features/messaging/vitest.config.ts,
libs/backend/features/notifications/vitest.config.ts,
libs/backend/features/settings/vitest.config.ts, and
libs/backend/features/social-media/vitest.config.ts, leaving each include
pattern unchanged so zero matched specs fail fast.

Comment on lines +7 to +11
test: {
globals: false,
environment: 'node',
include: ['src/**/*.spec.ts'],
passWithNoTests: true,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not allow these feature test projects to pass with zero discovered tests.

Both configurations enable passWithNoTests, so a mis-scoped test include can produce green CI without executing coverage. Vitest explicitly suppresses failure when no tests are found. (vitest.dev)

  • libs/backend/features/analytics/vitest.config.ts#L7-L11: remove passWithNoTests or override it to false in CI.
  • libs/backend/features/employee/vitest.config.ts#L7-L11: remove passWithNoTests or override it to false in CI.
📍 Affects 2 files
  • libs/backend/features/analytics/vitest.config.ts#L7-L11 (this comment)
  • libs/backend/features/employee/vitest.config.ts#L7-L11
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/backend/features/analytics/vitest.config.ts` around lines 7 - 11,
Prevent zero-test Vitest projects from passing by removing passWithNoTests or
explicitly setting it to false in the test configuration at
libs/backend/features/analytics/vitest.config.ts lines 7-11 and
libs/backend/features/employee/vitest.config.ts lines 7-11.

Source: MCP tools

Comment on lines +116 to +127
describe('TemporaryRoleElevation', () => {
it('should throw error if elevation expiry date is in the past', async () => {
const pastDate = new Date(Date.now() - 1000 * 60);

await expect(
service.grantTemporaryRoleElevation(
'emp-1',
['role-elevation'],
pastDate as unknown as string & Date,
),
).rejects.toThrow('Temporary role elevation must expire in the future');
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Argument shape mismatch masked by unsafe cast.

This call passes ['role-elevation'] (array) as the roleId arg and only 3 positional args, while the same method is called at lines 137-143 with a plain string and 5 args (actorId, reason included). The pastDate as unknown as string & Date cast is a red flag — that intersection type can't be legitimately satisfied, suggesting this was patched to silence a compiler error caused by the mismatched roleId argument rather than fixing the actual call shape.

🔧 Proposed fix to align with the correctly-typed call
       await expect(
         service.grantTemporaryRoleElevation(
           'emp-1',
-          ['role-elevation'],
-          pastDate as unknown as string & Date,
+          'role-elevation',
+          pastDate,
         ),
       ).rejects.toThrow('Temporary role elevation must expire in the future');
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
describe('TemporaryRoleElevation', () => {
it('should throw error if elevation expiry date is in the past', async () => {
const pastDate = new Date(Date.now() - 1000 * 60);
await expect(
service.grantTemporaryRoleElevation(
'emp-1',
['role-elevation'],
pastDate as unknown as string & Date,
),
).rejects.toThrow('Temporary role elevation must expire in the future');
});
describe('TemporaryRoleElevation', () => {
it('should throw error if elevation expiry date is in the past', async () => {
const pastDate = new Date(Date.now() - 1000 * 60);
await expect(
service.grantTemporaryRoleElevation(
'emp-1',
'role-elevation',
pastDate,
),
).rejects.toThrow('Temporary role elevation must expire in the future');
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@libs/backend/features/employee/src/lib/employee-role-assignment.service.spec.ts`
around lines 116 - 127, Correct the TemporaryRoleElevation test call to
grantTemporaryRoleElevation by passing a single role ID string and all required
positional arguments, including actorId and reason, matching the valid
invocation later in the suite. Remove the unsafe pastDate cast and pass the Date
value using the method’s actual parameter type.

}

publish(event: NotificationEvent) {
this.events$.next(event);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the notification transport service and related tests.
git ls-files 'libs/backend/features/notifications/src/lib/*' 'libs/backend/features/notifications/**/*test*' 'libs/backend/features/notifications/**/*spec*'

printf '\n--- notification-transport.service.ts ---\n'
wc -l libs/backend/features/notifications/src/lib/notification-transport.service.ts
cat -n libs/backend/features/notifications/src/lib/notification-transport.service.ts | sed -n '1,220p'

printf '\n--- search for related notification transport tests/usages ---\n'
rg -n "notification-transport|events\\$|swift-shop:commerce:notifications|publish\\(" libs/backend/features/notifications -g '!**/dist/**' -g '!**/build/**'

Repository: tahiry-dev-29/Swift-Shop

Length of output: 7694


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- notification-transport.service.spec.ts ---'
wc -l libs/backend/features/notifications/src/lib/notification-transport.service.spec.ts
cat -n libs/backend/features/notifications/src/lib/notification-transport.service.spec.ts | sed -n '1,220p'

printf '\n%s\n' '--- notification.service.spec.ts references to transport.publish ---'
wc -l libs/backend/features/notifications/src/lib/notification.service.spec.ts
cat -n libs/backend/features/notifications/src/lib/notification.service.spec.ts | sed -n '1,260p'

printf '\n%s\n' '--- notification-resolver.integration.spec.ts references to transport stream ---'
wc -l libs/backend/features/notifications/src/lib/notification-resolver.integration.spec.ts
cat -n libs/backend/features/notifications/src/lib/notification-resolver.integration.spec.ts | sed -n '1,260p'

Repository: tahiry-dev-29/Swift-Shop

Length of output: 14933


Avoid double-emitting Redis-published notifications publish() pushes to events$ directly and also publishes to swift-shop:commerce:notifications, which this same service subscribes to on subClient. That replays the same event into the subject and delivers it twice to SSE listeners. Emit through one path only, or add origin-based deduplication.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@libs/backend/features/notifications/src/lib/notification-transport.service.ts`
at line 71, Update the notification flow around the service’s publish method and
events$ subscription so Redis-published events are emitted to events$ only once.
Remove the direct emission or prevent the subClient Redis callback from
re-emitting events originating from publish(), while preserving delivery for
externally published notifications.

Comment on lines +66 to +85
describe('joinChat', () => {
it('should create new live chat session if sessionId is omitted', async () => {
prismaMock.liveChatSession.create.mockResolvedValue({
id: 'new-session-id',
customerId: 'cust-1',
status: 'ACTIVE',
});

const res = await gateway.joinChat(
{ customerId: 'cust-1' },
mockSocket as unknown as Socket,
);

expect(prismaMock.liveChatSession.create).toHaveBeenCalled();
expect(mockSocket.join).toHaveBeenCalledWith('new-session-id');
expect(res).toEqual({
event: 'joined',
data: { sessionId: 'new-session-id' },
});
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect the gateway implementation to confirm identity is derived from the token, not client input.
fd -e ts live-chat.gateway.ts
ast-grep run --pattern 'joinChat($_, $_) { $$$ }' --lang typescript libs/backend/features/support/src/lib/live-chat.gateway.ts

Repository: tahiry-dev-29/Swift-Shop

Length of output: 537


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the gateway file and inspect the relevant implementation and tests.
ast-grep outline libs/backend/features/support/src/lib/live-chat.gateway.ts --view expanded || true
echo '--- live-chat.gateway.ts ---'
grep -n "joinChat\|handshake\|auth\|customerId\|token" -n libs/backend/features/support/src/lib/live-chat.gateway.ts || true
echo '--- live-chat.gateway.spec.ts ---'
grep -n "joinChat\|handshake\|auth\|customerId\|token" -n libs/backend/features/support/src/lib/live-chat.gateway.spec.ts || true

# Read the relevant file sections with line numbers.
echo '--- gateway excerpt ---'
nl -ba libs/backend/features/support/src/lib/live-chat.gateway.ts | sed -n '1,220p'
echo '--- spec excerpt ---'
nl -ba libs/backend/features/support/src/lib/live-chat.gateway.spec.ts | sed -n '1,180p'

Repository: tahiry-dev-29/Swift-Shop

Length of output: 1525


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- live-chat.gateway.ts (lines 1-120) ---'
sed -n '1,120p' libs/backend/features/support/src/lib/live-chat.gateway.ts

echo '--- live-chat.gateway.spec.ts (lines 1-120) ---'
sed -n '1,120p' libs/backend/features/support/src/lib/live-chat.gateway.spec.ts

Repository: tahiry-dev-29/Swift-Shop

Length of output: 6680


Bind customerId to the authenticated socket, not the payload. joinChat currently persists data.customerId as-is, so any connected client can create a session under an arbitrary customer identity. Derive the customer from the verified token/context, or reject mismatches, before creating the session.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@libs/backend/features/support/src/lib/live-chat.gateway.spec.ts` around lines
66 - 85, Update the joinChat test and implementation contract so the customer
identity comes from the authenticated socket context rather than the request
payload. In joinChat, derive the verified customerId from the socket
authentication data or reject when the payload customerId does not match before
calling liveChatSession.create; update the test setup and assertions to cover
this authenticated identity.

Comment thread vitest.config.ts Outdated
test: {
projects: [
'apps/*/vite.config.mts',
'apps/*/vitest.config.ts',

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## vitest configs\n'
git ls-files '**/vitest.config.ts' '**/.github/workflows/*' '**/package.json' | sed 's#^`#-` #'

printf '\n## root vitest config\n'
if [ -f vitest.config.ts ]; then
  cat -n vitest.config.ts
fi

printf '\n## search for vitest run command and config includes\n'
rg -n "vitest run|apps/\*/vitest\.config\.ts|apps/api|libs/backend" .github vitest.config.ts package.json apps libs -g '!**/node_modules/**'

Repository: tahiry-dev-29/Swift-Shop

Length of output: 5545


🏁 Script executed:

#!/bin/bash
set -euo pipefail

set -x
pwd
git ls-files | rg '(^|/)(vitest\.config\.ts|package\.json|\.github/workflows/.*\.ya?ml)$'
printf '\n--- root vitest.config.ts ---\n'
cat -n vitest.config.ts
printf '\n--- CI references ---\n'
rg -n "bunx vitest run|vitest run|libs/backend|apps/api|apps/\*/vitest\.config\.ts" .github vitest.config.ts package.json

Repository: tahiry-dev-29/Swift-Shop

Length of output: 3096


🌐 Web query:

Vitest CLI path filter positional argument project config run file filter docs

💡 Result:

In Vitest, you can use positional arguments in the CLI to filter which test files to run [1][2]. When you pass a string as a positional argument (e.g., vitest foobar), Vitest runs only the test files that contain that string in their path [1][3]. This filter performs a simple inclusion check and does not support regex or glob patterns directly, unless your terminal resolves them before Vitest receives the argument [1][3]. For more precise filtering, you can also specify a file path combined with a specific line number to run only a particular test [1][4]. For example: vitest path/to/file.test.ts:10 Regarding project configuration, Vitest automatically searches for configuration files such as vitest.config.{ts,mts,cts,js,mjs,cjs} or vite.config.{ts,mts,cts,js,mjs,cjs} in your project root [5][6]. You can explicitly specify a configuration file using the --config CLI option (e.g., vitest --config./custom.config.ts) [5][6]. If you need to filter tests by name rather than path, you can use the -t or --testNamePattern option, which accepts a regex pattern [2][7]. This can be combined with file path filters to narrow down the execution [2][7]: vitest utils -t "handles empty input" Finally, for listing tests without running them, the vitest list command inherits the same file filter and name pattern options as the standard vitest command [1][3]. You can also pass the --filesOnly flag to vitest list to display only the matching file names [1][3].

Citations:


Include apps/api in the CI Vitest command
bunx vitest run libs/backend filters by path, so it won’t run apps/api/vitest.config.ts or apps/api/src/health/health.controller.spec.ts. Add apps/api to the command or remove the path filter.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@vitest.config.ts` at line 7, Update the CI Vitest command to include the
apps/api project so apps/api/vitest.config.ts and health.controller.spec.ts are
executed; either add apps/api to the existing path arguments or remove the
restrictive libs/backend filter.

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.

1 participant