Skip to content

test(auth, shopping): add unit tests for services#134

Open
varshapandiann wants to merge 1 commit into
omatheusmesmo:mainfrom
varshapandiann:feature/issue-34-unit-tests
Open

test(auth, shopping): add unit tests for services#134
varshapandiann wants to merge 1 commit into
omatheusmesmo:mainfrom
varshapandiann:feature/issue-34-unit-tests

Conversation

@varshapandiann

@varshapandiann varshapandiann commented Jun 11, 2026

Copy link
Copy Markdown

Closes #34

Added unit tests for AuthService and ShoppingListService to achieve 80% code coverage. Verified that all tests pass and follow project standards by running npm run test:ci, npm run lint, and npm run prettier.

Summary by CodeRabbit

  • Tests
    • Added/extended unit tests for authentication, covering successful login, invalid-login error handling, token persistence, and logout navigation.
    • Added unit tests for the shopping list service, covering fetching shopping lists and adding list items with expected API requests/responses.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 3a889e57-7e21-46c2-8739-fdadf120ceb6

📥 Commits

Reviewing files that changed from the base of the PR and between c87de2a and 9cde199.

📒 Files selected for processing (2)
  • frontend/src/app/shared/services/auth.service.spec.ts
  • frontend/src/app/shared/services/shopping-list.service.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • frontend/src/app/shared/services/shopping-list.service.spec.ts
  • frontend/src/app/shared/services/auth.service.spec.ts

📝 Walkthrough

Walkthrough

This PR adds Jasmine unit tests for AuthService (login success and failure, logout and token persistence) and ShoppingListService (getAllShoppingLists and addListItem), with HttpClientTestingModule setup and httpMock.verify() cleanup.

Changes

Core Service Unit Tests

Layer / File(s) Summary
AuthService unit tests
frontend/src/app/shared/services/auth.service.spec.ts
TestBed configured with HttpClientTestingModule, AuthService provided with a router mock; tests cover successful POST /api/auth/login (mock JWT emitted and persisted to localStorage under auth_token), 403 login error (Credenciais inválidas), logout() clearing token and navigating to ['/login'], and httpMock.verify() cleanup.
ShoppingListService unit tests
frontend/src/app/shared/services/shopping-list.service.spec.ts
TestBed injects ShoppingListService and HttpTestingController; tests cover getAllShoppingLists() issuing GET /lists and returning mocked ShoppingListResponseDTO data, and addListItem() issuing POST /lists/{listId}/items and returning mocked ListItemResponseDTO data, with httpMock.verify() cleanup.

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

From my burrow I hopped to test and play,
Tokens saved and cleared along the way.
Lists fetched, items posted with delight,
Assertions passing through the night.
🥕🐇

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'test(auth, shopping): add unit tests for services' accurately and concisely describes the main change: adding unit tests for AuthService and ShoppingListService.
Linked Issues check ✅ Passed The PR implements unit tests for AuthService and ShoppingListService, directly addressing the primary objective of issue #34 to replace scaffold files with functional unit tests for core services.
Out of Scope Changes check ✅ Passed All changes are in-scope: two new spec files for AuthService and ShoppingListService testing, directly aligned with issue #34's requirements to implement unit tests for these services.
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

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.

@github-actions github-actions 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.

🤖🎉 Thank you for your contribution! Your pull request has been submitted successfully. A maintainer from the team will review it as soon as possible. We appreciate your support in making this project better!

@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)
frontend/src/app/shared/services/shopping-list.service.spec.ts (2)

57-59: ⚡ Quick win

Assert POST payload to lock the API contract.

Line 57-59 validate URL/method, but not request body. Add a body assertion so the test fails if DTO mapping regresses.

Suggested patch
     const req = httpMock.expectOne(`${apiUrl}/1/items`);
     expect(req.request.method).toBe('POST');
+    expect(req.request.body).toEqual(mockItemRequest);
     req.flush(mockItemResponse);
🤖 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 `@frontend/src/app/shared/services/shopping-list.service.spec.ts` around lines
57 - 59, The test currently checks the URL and method but not the POST body;
after calling httpMock.expectOne(`${apiUrl}/1/items`) and before
req.flush(mockItemResponse) add an assertion that req.request.body strictly
equals the DTO you send in the service call (e.g., the newItem or
mockItemRequest object used in the spec) so changes to the request mapping will
fail the test; update the spec in shopping-list.service.spec.ts around the
existing expectOne/req.sequence to assert req.request.body === expectedPayload.

22-60: ⚡ Quick win

Add error-path specs for both service methods.

Current tests only cover success responses. Add HTTP error cases (e.g., 400/500) for getAllShoppingLists() and addListItem() to validate behavior through catchError(...) in the service and improve confidence in failure handling.

🤖 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 `@frontend/src/app/shared/services/shopping-list.service.spec.ts` around lines
22 - 60, Add unit tests that exercise the error paths for
service.getAllShoppingLists() and service.addListItem(): simulate HTTP errors
(e.g., 400 and 500) via httpMock.expectOne(...).flush(..., { status, statusText
}) and assert the Observables emit the expected error handling behavior
(subscribe error callback or transformed value returned by the service's
catchError). Locate tests around the existing specs for getAllShoppingLists and
addListItem and add one failing-case test for each that verifies the service's
catchError logic (e.g., error message, rethrow, or fallback value) for
getAllShoppingLists() and for addListItem() using the same request URLs used in
the success tests.
🤖 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 `@frontend/src/app/shared/services/auth.service.spec.ts`:
- Around line 12-16: Replace the inline jasmine spy "routerSpy" with the
project's shared Router mock: import the shared Router mock (e.g., mockRouter)
and use it in TestBed.configureTestingModule providers instead of creating
routerSpy, keeping AuthService in providers; remove the local
jasmine.createSpyObj call and update any references to routerSpy in the spec to
use the shared mock instance.

---

Nitpick comments:
In `@frontend/src/app/shared/services/shopping-list.service.spec.ts`:
- Around line 57-59: The test currently checks the URL and method but not the
POST body; after calling httpMock.expectOne(`${apiUrl}/1/items`) and before
req.flush(mockItemResponse) add an assertion that req.request.body strictly
equals the DTO you send in the service call (e.g., the newItem or
mockItemRequest object used in the spec) so changes to the request mapping will
fail the test; update the spec in shopping-list.service.spec.ts around the
existing expectOne/req.sequence to assert req.request.body === expectedPayload.
- Around line 22-60: Add unit tests that exercise the error paths for
service.getAllShoppingLists() and service.addListItem(): simulate HTTP errors
(e.g., 400 and 500) via httpMock.expectOne(...).flush(..., { status, statusText
}) and assert the Observables emit the expected error handling behavior
(subscribe error callback or transformed value returned by the service's
catchError). Locate tests around the existing specs for getAllShoppingLists and
addListItem and add one failing-case test for each that verifies the service's
catchError logic (e.g., error message, rethrow, or fallback value) for
getAllShoppingLists() and for addListItem() using the same request URLs used in
the success 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 030b131d-43b1-4b11-8c3b-d1923bea1a4e

📥 Commits

Reviewing files that changed from the base of the PR and between 4b3dd65 and 330b30a.

📒 Files selected for processing (2)
  • frontend/src/app/shared/services/auth.service.spec.ts
  • frontend/src/app/shared/services/shopping-list.service.spec.ts

Comment thread frontend/src/app/shared/services/auth.service.spec.ts Outdated
@varshapandiann varshapandiann force-pushed the feature/issue-34-unit-tests branch from 3bfafc4 to c87de2a Compare June 17, 2026 16:37
@matheusandre1

Copy link
Copy Markdown
Collaborator

LGTM! @varshapandiann squash commit please!

test(auth): use shared MockRouter from shared mocks

style: fix formatting issues
@varshapandiann varshapandiann force-pushed the feature/issue-34-unit-tests branch from c87de2a to 9cde199 Compare June 18, 2026 07:47
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.

QA: Implement Unit Tests for core services

2 participants