Skip to content

Write tests for log in - #190

Merged
Kahn32 merged 11 commits into
mainfrom
write-tests-landing-signup
Dec 3, 2025
Merged

Write tests for log in#190
Kahn32 merged 11 commits into
mainfrom
write-tests-landing-signup

Conversation

@hiuyear

@hiuyear hiuyear commented Dec 2, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Tests
    • Added comprehensive LoginPage tests covering UI elements, input handling, loading state behavior, success and error messaging, form validation, error clearing between attempts, and navigation after successful login.

✏️ Tip: You can customize this high-level summary in your review settings.

Copilot AI review requested due to automatic review settings December 2, 2025 23:44
@vercel

vercel Bot commented Dec 2, 2025

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
cybermetrics Ready Ready Preview Comment Dec 2, 2025 11:53pm

@coderabbitai

coderabbitai Bot commented Dec 2, 2025

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds a comprehensive Vitest + React Testing Library suite for the LoginPage that mocks authActions.login and react-router's useNavigate, covering static UI, input handling, loading state, success/error flows, form validation, and error message lifecycle.

Changes

Cohort / File(s) Change Summary
LoginPage Test Suite
client/src/pages/LoginPage/LoginPage.test.tsx
Adds a full test suite for the LoginPage component: static UI assertions, email/password input handling, loading-state behavior, success and error handling (including undefined error cases), form validation, error lifecycle, and navigation checks. Mocks authActions.login and useNavigate.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Review test cases for correct use of async utilities (waitFor) and cleanup of mocks between tests.
  • Verify mock implementations for authActions.login simulate intended outcomes (success, specific errors, undefined errors).
  • Confirm navigation assertions and route expectations align with app routing (team builder/lineup path).
  • Check accessibility-related assertions (labels, autocomplete) and that loading/disabled states are asserted consistently.

Poem

🐰 I hopped through tests both day and night,

typing emails, passwords tight.
Mocks and waits in orderly rows,
success, errors, each case shows —
a tiny rabbit cheers: "All green light!" ✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title 'Write tests for log in' accurately describes the main change: adding a comprehensive test suite for the LoginPage component.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch write-tests-landing-signup

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e6f7bd and 464fa12.

📒 Files selected for processing (1)
  • client/src/pages/LoginPage/LoginPage.test.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • client/src/pages/LoginPage/LoginPage.test.tsx

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.

@hiuyear hiuyear changed the title Write tests landing signup Write tests for log in Dec 2, 2025
@hiuyear hiuyear self-assigned this Dec 2, 2025
@hiuyear
hiuyear requested a review from Kahn32 December 2, 2025 23:45

This comment was marked as outdated.

@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: 0

🧹 Nitpick comments (6)
client/src/pages/LoginPage/LoginPage.test.tsx (6)

1-20: Mocks are fine; consider explicit factory for authActions for clarity

Right now vi.mock('@/actions/auth') relies on Vitest’s auto-mocking behavior. Defining the mock shape explicitly makes the tests more robust and self-documenting, and avoids surprises if the real module changes:

-// Mock dependencies
-vi.mock('@/actions/auth');
+// Mock dependencies
+vi.mock('@/actions/auth', () => ({
+  authActions: {
+    login: vi.fn(),
+  },
+}));

This also guarantees authActions.login is always a vi.fn() without depending on module implementation details.


58-67: Minor misleading comment in password typing test

The test itself correctly verifies password field typing, but the inline comment on Line 62 refers to disabling inputs while loading, which doesn’t match this test’s behavior and may confuse future readers.

You can safely drop or update that comment:

-    // disable form inputs while loading

69-94: Loading-state test works; consider avoiding real timers in the mock

This test correctly asserts that inputs and the button are disabled and that the loading label appears while the login promise is pending. One small improvement is to avoid the setTimeout-based implementation in the mock, which introduces a real-time delay and can create state updates after the test finishes.

You could instead return a never-resolving promise to keep the component in loading state without delayed updates:

-    vi.mocked(authActions.login).mockImplementation(() => 
-      new Promise(resolve => setTimeout(() => resolve({ 
-        success: true,
-        data: { token: 'fake-token' } as any 
-      }), 100))
-    );
+    vi.mocked(authActions.login).mockImplementation(
+      () => new Promise(() => {}) as Promise<{ success: true }>
+    );

This keeps isLoading true for the duration of the test without side-effectful resolution.


96-114: Test name mentions navigation but only asserts success message + login call

The test currently verifies that the success message appears and authActions.login is called with the right credentials, but the description says “and navigates on successful login”.

Either:

  • Rename the test to match what it actually asserts, or
  • Also assert navigation (and possibly reuse mockNavigate) here, if you prefer to couple success and navigation checks in one place.

Given you already have a dedicated navigation test later, renaming is likely the simpler option.


152-160: Empty-fields test only checks required attributes; consider asserting no submit

The test name implies that form submission is prevented, but the assertions only verify the required attributes. To tighten this test and better reflect its description, you could simulate a submit and assert that authActions.login is not called:

-  it('prevents form submission when fields are empty', () => {
-    renderLoginPage();
-    
-    const emailInput = screen.getByLabelText('Email') as HTMLInputElement;
-    const passwordInput = screen.getByLabelText('Password') as HTMLInputElement;
-    
-    expect(emailInput).toBeRequired();
-    expect(passwordInput).toBeRequired();
-  });
+  it('prevents form submission when fields are empty', async () => {
+    const user = userEvent.setup();
+    renderLoginPage();
+
+    const submitButton = screen.getByRole('button', { name: 'Login' });
+    await user.click(submitButton);
+
+    expect(authActions.login).not.toHaveBeenCalled();
+  });

You can keep a separate test for required attributes if you still want that coverage explicitly.


193-215: Navigation test works; consider fake timers to avoid real 1s delay

The test correctly verifies that a successful login eventually calls mockNavigate with ROUTES.LINEUP_CONSTRUCTOR. Since the component uses a 1-second setTimeout, this test currently incurs real-time delay and relies on a 2-second waitFor timeout.

You can make this faster and more deterministic using fake timers, e.g.:

-  it('navigates to team builder after successful login', async () => {
-  const user = userEvent.setup();
+  it('navigates to team builder after successful login', async () => {
+  vi.useFakeTimers();
+  const user = userEvent.setup();-  await waitFor(() => {
-    expect(screen.getByText('Login successful!')).toBeInTheDocument();
-  });
-  
-  // Wait for setTimeout navigation
-  await waitFor(() => {
-    expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LINEUP_CONSTRUCTOR);
-  }, { timeout: 2000 });
+  await waitFor(() => {
+    expect(screen.getByText('Login successful!')).toBeInTheDocument();
+  });
+
+  // Fast‑forward the navigation timeout
+  vi.advanceTimersByTime(1000);
+  expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LINEUP_CONSTRUCTOR);
+  vi.useRealTimers();

Please double‑check exact fake‑timer APIs (advanceTimersByTime vs async variants) against your Vitest version.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1aa1a98 and 7e6f7bd.

📒 Files selected for processing (1)
  • client/src/pages/LoginPage/LoginPage.test.tsx (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
client/src/pages/LoginPage/LoginPage.test.tsx (3)
client/src/pages/LoginPage/LoginPage.tsx (1)
  • LoginPage (17-102)
client/src/config/constants.ts (1)
  • ROUTES (9-16)
client/src/actions/auth.ts (1)
  • authActions (3-83)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Agent
🔇 Additional comments (7)
client/src/pages/LoginPage/LoginPage.test.tsx (7)

21-32: Test suite setup and helper renderer look good

The beforeEach with vi.clearAllMocks() plus the renderLoginPage helper that wraps with BrowserRouter keeps the tests isolated and avoids boilerplate in each case. No changes needed here.


34-46: Solid coverage of static login UI

This test does a good job asserting key headings, labels, call-to-action text, and the signup link target (ROUTES.SIGNUP), which will catch most accidental UI regressions in the login shell.


48-56: Email input typing behavior test is clear and sufficient

Verifying the email field value after user.type is a straightforward, component-level sanity check and aligns with how the field is labeled. Looks good as-is.


116-132: Failed-login error flow test is solid

The mock result and assertion of 'Invalid credentials' match the expected behavior for a failed login. This is a good, minimal coverage of the negative path; no changes needed.


134-150: Generic error behavior for undefined error is well covered

Mocking success: false without an error field and asserting 'An error occurred' matches the described fallback behavior. This nicely protects against unexpected backend error shapes.


162-184: Error-clearing behavior between submissions is well tested

Chaining mockResolvedValueOnce for two different error messages and asserting that the first error disappears while the second appears ensures the component resets error state correctly on resubmission. This is a nice coverage of subtle UX behavior.


186-191: Autocomplete attributes test is concise and valuable

Asserting autocomplete="email" and "current-password" on the respective fields is a good accessibility/UX check and guards against accidental attribute regression. No changes needed.

@hiuyear

hiuyear commented Dec 3, 2025

Copy link
Copy Markdown
Collaborator Author

@copilot review

@TeamCybermetrics TeamCybermetrics deleted a comment from coderabbitai Bot Dec 3, 2025
@TeamCybermetrics TeamCybermetrics deleted a comment from Copilot AI Dec 3, 2025

@Kahn32 Kahn32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Tests Look good to me

@Kahn32
Kahn32 merged commit f873698 into main Dec 3, 2025
5 checks passed
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.

3 participants