Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: ReCAPTCHA refresh on submitting Login/SignUp form #2943

Conversation

PratapRathi
Copy link
Contributor

@PratapRathi PratapRathi commented Dec 26, 2024

What kind of change does this PR introduce?

  1. This PR will achieve the expected behaviour - After submitting Login/SignUp form with wrong credentials, Google ReCAPTCHA must reset so the person can login again with correct credentials without reloading the page
  2. Also its Unit test added to prevent breakage in future.
  3. LoginPage.test.tsx migrated to Vitest

Issue Number:
Fixes #2928 & #2554

Did you add tests for your changes?
Yes

Snapshots/Videos:

Screen.Recording.2024-12-26.at.22.52.55.mov

If relevant, did you update the documentation?
No

Summary
Does this PR introduce a breaking change?
No

Other information
N/A

Have you read the contributing guide?

Yes

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Enhanced ReCAPTCHA functionality on the Login and Signup pages to reset upon successful or failed attempts.
  • Bug Fixes

    • Improved error handling for login and signup processes, ensuring ReCAPTCHA resets appropriately on errors.
  • Tests

    • Updated test suite for the LoginPage component, including enhanced asynchronous testing and new test cases for ReCAPTCHA functionality.

Copy link
Contributor

coderabbitai bot commented Dec 26, 2024

Walkthrough

The pull request introduces modifications to the LoginPage component and its test suite, focusing on two primary changes: migrating the test framework from Jest to Vitest and implementing ReCAPTCHA reset functionality. In the LoginPage.tsx, two useRef hooks are added to manage ReCAPTCHA references for login and signup forms, enabling dynamic reset of the ReCAPTCHA component after submission attempts. The corresponding test file LoginPage.spec.tsx is updated to use Vitest's mocking and testing syntax, ensuring compatibility with the new testing framework.

Changes

File Change Summary
src/screens/LoginPage/LoginPage.tsx Added loginRecaptchaRef and SignupRecaptchaRef to manage ReCAPTCHA reset functionality.
src/screens/LoginPage/LoginPage.spec.tsx Migrated from Jest to Vitest, updated mocking and test definition syntax, added new test cases for ReCAPTCHA functionality.

Assessment against linked issues

Objective Addressed Explanation
ReCAPTCHA Reset after Failed Login/SignUp [#2928]
Migrate LoginPage Tests to Vitest [#2554]

Possibly related issues

Possibly related PRs

Suggested reviewers

  • palisadoes
  • varshith257

Poem

🐰 A Rabbit's Ode to ReCAPTCHA's Dance
In LoginPage's realm of code so bright,
ReCAPTCHA now resets with might!
From Jest to Vitest, tests take flight,
No more page reloads, what a delight! 🎉
Hop, hop, hooray for cleaner design! 🐇


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a463730 and 29e951c.

📒 Files selected for processing (2)
  • src/screens/LoginPage/LoginPage.spec.tsx (29 hunks)
  • src/screens/LoginPage/LoginPage.tsx (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/screens/LoginPage/LoginPage.tsx
  • src/screens/LoginPage/LoginPage.spec.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (1)
src/screens/LoginPage/LoginPage.spec.tsx (1)

1024-1028: Consider verifying fetch error response details as well.

Clearing mocks is good. For completeness, you might also want to assert that an appropriate user-facing error message – or a relevant toast – is displayed when the fetch fails.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0cede94 and 2fcfe56.

📒 Files selected for processing (2)
  • src/screens/LoginPage/LoginPage.spec.tsx (29 hunks)
  • src/screens/LoginPage/LoginPage.tsx (6 hunks)
🔇 Additional comments (7)
src/screens/LoginPage/LoginPage.spec.tsx (4)

27-27: Good use of Vitest imports.

You've successfully replaced Jest dependencies with the Vitest counterparts (vi, beforeEach, expect, it, describe). Ensure you remove or adapt any leftover Jest-specific config or scripts to avoid confusion.


218-220: Mocking strategy looks correct.

Your mocks for react-toastify follow best practices for partial mocking. This ensures test isolation and consistency.


Line range hint 236-253: Comprehensive ReCAPTCHA mock.

This approach correctly simulates reset functionality in the mock and provides full control needed for testing. Great job.


634-665: ReCAPTCHA reset test is well-structured.

Verifying resetReCAPTCHA is called after an unsuccessful login aligns perfectly with the PR's objective. The test ensures the fix won't regress in the future.

src/screens/LoginPage/LoginPage.tsx (3)

64-65: ReCAPTCHA refs add clarity for separate login and signup flows.

Using two distinct refs, loginRecaptchaRef and SignupRecaptchaRef, is a clean way to isolate recaptcha resets for each form.


259-263: Resetting ReCAPTCHA on signup exceptions.

Great job resetting ReCAPTCHA upon both successful and failed signup attempts. This ensures a consistent user experience.


335-339: Resetting ReCAPTCHA on login exceptions.

Similarly, resetting the ReCAPTCHA upon login errors helps clear the stale token for subsequent login tries.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 26, 2024
Copy link

codecov bot commented Dec 26, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 1 line in your changes missing coverage. Please review.

Project coverage is 88.60%. Comparing base (35cce16) to head (29e951c).
Report is 33 commits behind head on develop-postgres.

Files with missing lines Patch % Lines
src/screens/LoginPage/LoginPage.tsx 80.00% 1 Missing ⚠️
Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #2943       +/-   ##
=====================================================
+ Coverage             58.52%   88.60%   +30.08%     
=====================================================
  Files                   299      316       +17     
  Lines                  7414     8278      +864     
  Branches               1621     1813      +192     
=====================================================
+ Hits                   4339     7335     +2996     
+ Misses                 2828      721     -2107     
+ Partials                247      222       -25     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

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 (2)
src/screens/LoginPage/LoginPage.spec.tsx (2)

Line range hint 235-277: Consider simplifying the ReCAPTCHA mock implementation

The current mock implementation is quite complex. Consider simplifying it by directly mocking the reset function without the full component implementation.

-const recaptcha = react.forwardRef(
-  (
-    props: {
-      onChange: (value: string) => void;
-    } & React.InputHTMLAttributes<HTMLInputElement>,
-    ref: React.LegacyRef<HTMLInputElement> | undefined,
-  ): JSX.Element => {
-    const { onChange, ...otherProps } = props;
-
-    Object.defineProperty(ref, 'current', {
-      value: {
-        reset: resetReCAPTCHA,
-      },
-    });
-
-    const handleChange = (
-      event: React.ChangeEvent<HTMLInputElement>,
-    ): void => {
-      if (onChange) {
-        onChange(event.target.value);
-      }
-    };
-
-    return (
-      <>
-        <input
-          type="text"
-          data-testid="mock-recaptcha"
-          {...otherProps}
-          onChange={handleChange}
-          ref={ref}
-        />
-      </>
-    );
-  },
-);
+const recaptcha = react.forwardRef((props, ref) => {
+  Object.defineProperty(ref, 'current', {
+    value: { reset: resetReCAPTCHA },
+  });
+  return <input data-testid="mock-recaptcha" {...props} />;
+});

Line range hint 1024-1061: Enhance error handling test coverage

The API error handling tests could be more comprehensive:

  1. Different types of network errors
  2. Various HTTP status codes
  3. Invalid response formats
 it('displays warning message when resource loading fails', async () => {
-  const mockError = new Error('Network error');
-  global.fetch = vi.fn(() => Promise.reject(mockError));
+  // Test different error scenarios
+  const errorScenarios = [
+    { error: new Error('Network error'), desc: 'network error' },
+    { error: new Error('Timeout'), desc: 'timeout error' },
+    { error: new Response(null, { status: 404 }), desc: '404 status' },
+    { error: new Response(null, { status: 500 }), desc: '500 status' },
+  ];
+
+  for (const scenario of errorScenarios) {
+    global.fetch = vi.fn(() => 
+      scenario.error instanceof Error 
+        ? Promise.reject(scenario.error)
+        : Promise.resolve(scenario.error)
+    );

    await act(async () => {
      render(
        <MockedProvider addTypename={false} link={link}>
          <BrowserRouter>
            <Provider store={store}>
              <I18nextProvider i18n={i18nForTest}>
                <LoginPage />
              </I18nextProvider>
            </Provider>
          </BrowserRouter>
        </MockedProvider>,
      );
    });

    expect(fetch).toHaveBeenCalledWith(BACKEND_URL);
+    // Add specific assertions for each error scenario
+    // Clean up after each scenario
+    cleanup();
+  }
 });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2fcfe56 and a463730.

📒 Files selected for processing (1)
  • src/screens/LoginPage/LoginPage.spec.tsx (29 hunks)
🔇 Additional comments (4)
src/screens/LoginPage/LoginPage.spec.tsx (4)

3-9: LGTM: Clean import organization

The imports are well-organized, and the addition of waitFor from @testing-library/react is appropriate for handling asynchronous operations in tests.


215-219: LGTM: Clean migration to Vitest mocking

The toast mock has been correctly migrated from Jest to Vitest, maintaining the same functionality while using the new framework's syntax.


633-664: LGTM: Comprehensive test coverage for ReCAPTCHA reset

The test case effectively verifies that the ReCAPTCHA component is reset after an unsuccessful login attempt. The use of waitFor ensures proper handling of asynchronous behavior.


Line range hint 1-1061: Verify test coverage for all LoginPage component features

The test suite appears comprehensive but should be verified against the component's features.

✅ Verification successful

Let me gather more information about the LoginPage component to verify test coverage.


Let me gather more information about the component's state and mutations to ensure complete coverage.


Based on the gathered information, I can now provide the final response:

Test coverage appears comprehensive for LoginPage component

The test suite provides thorough coverage of the LoginPage component's features:

  • Core functionality tests:

    • Login and registration form submissions
    • Password validation and error warnings
    • ReCAPTCHA integration
    • Role toggle (admin/user)
    • Form state management
    • Pre-login data handling
    • Password visibility toggles
    • Organization list integration
  • Edge cases and error scenarios:

    • Invalid input validation
    • Password mismatch scenarios
    • Failed API connections
    • Authentication redirects
    • ReCAPTCHA token handling
  • UI interaction tests:

    • Tab switching
    • Form field interactions
    • Password visibility toggles
    • Organization dropdown selection

The test suite covers all identified component features including state management, mutations, queries, form submissions, and user interactions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for LoginPage component features

# Find all props, handlers, and state in LoginPage component
echo "Searching for LoginPage component features..."
ast-grep --pattern 'const LoginPage = () => {
  $$$
}'

# Find all event handlers
echo "Searching for event handlers..."
ast-grep --pattern 'const handle$_($$$) {
  $$$
}'

# Compare with test coverage
echo "Searching for corresponding test cases..."
rg -l 'it\(' --type ts

Length of output: 9933


Script:

#!/bin/bash
# Find the LoginPage component implementation
echo "Searching for LoginPage component implementation..."
rg -A 10 "const LoginPage = \(\)" src/screens/LoginPage/LoginPage.tsx

# Find all event handlers in LoginPage
echo "Searching for event handlers in LoginPage..."
rg -A 5 "const handle[A-Z][a-zA-Z]+" src/screens/LoginPage/LoginPage.tsx

# Find all test cases in LoginPage.spec.tsx
echo "Searching for test cases in LoginPage.spec.tsx..."
rg "^  it\(" src/screens/LoginPage/LoginPage.spec.tsx

Length of output: 3463


Script:

#!/bin/bash
# Find state management in LoginPage
echo "Searching for state hooks in LoginPage..."
rg -A 2 "const \[.*?, set.*?\] = useState" src/screens/LoginPage/LoginPage.tsx

# Find mutations and queries
echo "Searching for GraphQL mutations and queries..."
rg -A 2 "const \[.*?Mutation\]" src/screens/LoginPage/LoginPage.tsx
rg -A 2 "const \{.*?\} = useQuery" src/screens/LoginPage/LoginPage.tsx

# Find form submission handlers
echo "Searching for form submissions..."
rg -A 5 "const.*?submit|onSubmit" src/screens/LoginPage/LoginPage.tsx

Length of output: 2227

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 26, 2024
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

Please add tests for these lines

image

@PratapRathi
Copy link
Contributor Author

@palisadoes I've added test case for Register functionality too. Ready for you review, guide me if I'm missing something.

@palisadoes palisadoes merged commit ab3b14f into PalisadoesFoundation:develop-postgres Dec 27, 2024
13 checks passed
@PratapRathi PratapRathi deleted the fix/Google-ReCAPTCH-reload-after-submit-login-form branch December 29, 2024 09:16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants