test(backend): add comprehensive unit and integration tests across all features#27
test(backend): add comprehensive unit and integration tests across all features#27tahiry-dev-29 wants to merge 0 commit into
Conversation
|
Caution The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased. |
📝 WalkthroughWalkthroughAdds 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. ChangesBackend test infrastructure
Authentication and authorization
Employee RBAC
Analytics and settings
Messaging and notifications
Social media and support
Backend checklist
Estimated code review effort: 4 (Complex) | ~60 minutes Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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.jsonTraceback (most recent call last): libs/backend/features/employee/tsconfig.jsonTraceback (most recent call last): libs/backend/features/employee/tsconfig.lib.jsonTraceback (most recent call last):
🔧 ESLint
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. Comment |
There was a problem hiding this comment.
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 winTighten
syncExchangeRatesassertion 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 valueMinor: mock return-value slugs are inconsistent with the asserted slugification. The
create/cloneRolecalls are asserted with underscore slugs (order_specialist,cloned_role), while the correspondingmockResolvedValuereturns hyphenated slugs (order-specialist,cloned-role). It's harmless today since onlyname/idare 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 valueThreshold value is hardcoded implicitly. Seeding
failedLoginAttempts: 4and expecting the update-to-5to trigger lockout couples this test toLOCKOUT_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 importedLOCKOUT_THRESHOLDconstant (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
📒 Files selected for processing (64)
.eslintrc.jsonapps/api/src/health/health.controller.spec.tsapps/api/vitest.config.tseslint.config.mjslibs/backend/core/auth/src/index.tslibs/backend/core/auth/src/lib/decorators/current-user.decorator.tslibs/backend/core/auth/src/lib/guards/auth-guards.spec.tslibs/backend/core/auth/src/lib/guards/store-branch-scope.guard.spec.tslibs/backend/core/auth/src/lib/services/auth-audit.service.spec.tslibs/backend/core/auth/src/lib/services/auth-credentials.service.spec.tslibs/backend/core/auth/src/lib/services/auth-integration.spec.tslibs/backend/core/auth/src/lib/services/auth-mail.service.spec.tslibs/backend/core/auth/src/lib/services/auth-oauth.service.spec.tslibs/backend/core/auth/src/lib/services/auth-recovery.service.spec.tslibs/backend/core/auth/src/lib/services/auth-token-security.spec.tslibs/backend/core/auth/src/lib/services/password-security.service.spec.tslibs/backend/core/auth/src/lib/services/trusted-device.service.spec.tslibs/backend/core/auth/src/lib/services/two-factor.service.spec.tslibs/backend/core/auth/vitest.config.tslibs/backend/features/analytics/src/lib/analytics.repository.spec.tslibs/backend/features/analytics/src/lib/analytics.resolver.integration.spec.tslibs/backend/features/analytics/src/lib/analytics.service.spec.tslibs/backend/features/analytics/vitest.config.tslibs/backend/features/customer/src/index.tslibs/backend/features/employee/src/index.tslibs/backend/features/employee/src/lib/employee-role-assignment.service.spec.tslibs/backend/features/employee/src/lib/role-permission.service.spec.tslibs/backend/features/employee/src/lib/role.service.spec.tslibs/backend/features/employee/tsconfig.jsonlibs/backend/features/employee/tsconfig.lib.jsonlibs/backend/features/employee/vitest.config.tslibs/backend/features/messaging/src/lib/processors/email.processor.spec.tslibs/backend/features/messaging/src/lib/resolvers/messaging-resolvers.integration.spec.tslibs/backend/features/messaging/src/lib/services/email-template.service.spec.tslibs/backend/features/messaging/src/lib/services/messaging.service.spec.tslibs/backend/features/messaging/tsconfig.jsonlibs/backend/features/messaging/tsconfig.lib.jsonlibs/backend/features/messaging/vitest.config.tslibs/backend/features/notifications/src/lib/notification-resolver.integration.spec.tslibs/backend/features/notifications/src/lib/notification-transport.service.spec.tslibs/backend/features/notifications/src/lib/notification-transport.service.tslibs/backend/features/notifications/src/lib/notification.service.spec.tslibs/backend/features/notifications/src/lib/push-notification.service.spec.tslibs/backend/features/notifications/src/lib/queue/notification-queue.service.spec.tslibs/backend/features/notifications/src/lib/sms-notification.service.spec.tslibs/backend/features/notifications/vitest.config.tslibs/backend/features/settings/src/lib/currency.service.spec.tslibs/backend/features/settings/src/lib/language.service.spec.tslibs/backend/features/settings/src/lib/resolvers/settings-resolvers.integration.spec.tslibs/backend/features/settings/src/lib/setting.service.spec.tslibs/backend/features/settings/vitest.config.tslibs/backend/features/social-media/src/lib/integrations/facebook.service.spec.tslibs/backend/features/social-media/src/lib/integrations/instagram.service.spec.tslibs/backend/features/social-media/src/lib/social-media.processor.spec.tslibs/backend/features/social-media/src/lib/social-media.resolver.integration.spec.tslibs/backend/features/social-media/src/lib/social-media.service.spec.tslibs/backend/features/social-media/vitest.config.tslibs/backend/features/support/src/lib/live-chat.gateway.spec.tslibs/backend/features/support/src/lib/support-ticket.formatter.tslibs/backend/features/support/src/lib/support-ticket.resolver.integration.spec.tslibs/backend/features/support/src/lib/support-ticket.service.spec.tslibs/backend/features/support/vitest.config.tstodos/01-backend.mdvitest.config.ts
| include: ['src/**/*.spec.ts'], | ||
| passWithNoTests: true, |
There was a problem hiding this comment.
🎯 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())
PYRepository: 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-L11libs/backend/features/notifications/vitest.config.ts#L10-L11libs/backend/features/settings/vitest.config.ts#L10-L11libs/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.
| test: { | ||
| globals: false, | ||
| environment: 'node', | ||
| include: ['src/**/*.spec.ts'], | ||
| passWithNoTests: true, |
There was a problem hiding this comment.
🎯 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: removepassWithNoTestsor override it tofalsein CI.libs/backend/features/employee/vitest.config.ts#L7-L11: removepassWithNoTestsor override it tofalsein 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
| 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'); | ||
| }); |
There was a problem hiding this comment.
🎯 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.
| 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); |
There was a problem hiding this comment.
🎯 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.
| 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' }, | ||
| }); | ||
| }); |
There was a problem hiding this comment.
🔒 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.tsRepository: 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.tsRepository: 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.
| test: { | ||
| projects: [ | ||
| 'apps/*/vite.config.mts', | ||
| 'apps/*/vitest.config.ts', |
There was a problem hiding this comment.
🎯 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.jsonRepository: 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:
- 1: https://vitest.dev/guide/cli
- 2: https://vitest.dev/guide/filtering
- 3: https://github.com/vitest-dev/vitest/blob/main/docs/guide/cli.md
- 4: vitest-dev/vitest@4d94b956
- 5: https://vitest.dev/config/
- 6: https://github.com/vitest-dev/vitest/blob/main/docs/config/index.md
- 7: https://github.com/vitest-dev/vitest/blob/main/docs/guide/filtering.md
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.
49abe59 to
e61e7f5
Compare
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
health.controller.spec.tsauth-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-factoranalytics.repository,analytics.resolver.integration,analytics.serviceemployee-role-assignment.service,role-permission.service,role.serviceemail.processor,messaging-resolvers.integration,email-template.service,messaging.servicenotification-resolver.integration,notification-transport.service,notification.service,push-notification.service,notification-queue.service,sms-notification.servicecurrency.service,language.service,settings-resolvers.integration,setting.servicefacebook.service,instagram.service,social-media.processor,social-media.resolver.integration,social-media.servicelive-chat.gateway,support-ticket.resolver.integration,support-ticket.serviceConfig & Setup
apps/api,auth (core),analytics,employee,messaging,notifications,settings,social-media,supportvitest.config.tsupdated to pick up API app vitest config.swcrcconfig added; migrated to@nx/vitestplugin andvite-plugin-static-copy/vite-tsconfig-pathsSource Fixes
auth/src/index.tsexport typeforJwtPayloadauth/current-user.decorator.tsimport type/export typeforAuthUserauth/vitest.config.tstsconfigPaths+ meilisearch aliascustomer/src/index.tsemployee/src/index.tsnotification-transport.service.tsthis.events$.next(event)inpublish()support-ticket.formatter.tscustomerId/employeeIdto formatted outputHousekeeping
01-backend.mdupdated with completed test checklist itemsTest Plan
Summary by CodeRabbit
Bug Fixes
Tests
Documentation