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: simplified error messages for invalid inputs at profile settings #2500

Open
wants to merge 20 commits into
base: develop-postgres
Choose a base branch
from

Conversation

bandhan-majumder
Copy link

@bandhan-majumder bandhan-majumder commented Nov 28, 2024

What kind of change does this PR introduce?

A bugfix.

Issue Number:

Fixes #2464

Snapshots/Videos:

https://www.loom.com/share/5e08e9042d43429788277eb8b30749ea?sid=c2f89415-db97-47e9-be29-0b99386cb2de

Passing all tests
image
Summary

While updating user profile at Talawa User Portal, user used not to get user friendly errors. I have simplified the error which will come one by one in a user friendly readable manner helping user to understand the fields they are missing/giving wrong data into. I have also added translation of errors.

Other information

Added a 400 handler too.

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • New Features

    • Added multiple new error messages for input validation across English, French, Hindi, Spanish, and Chinese locales.
    • Enhanced user feedback for various input scenarios, including phone number, education grade, employment status, and marital status.
  • Bug Fixes

    • Improved error handling logic to provide more specific feedback based on different error scenarios, including handling for status code 400.
  • Tests

    • Introduced new test cases for the error handling function to ensure accurate feedback for various error messages.

Copy link

coderabbitai bot commented Nov 28, 2024

Walkthrough

The pull request introduces new error messages across multiple localization files, including English, French, Hindi, Spanish, and Chinese. These messages enhance user feedback regarding input validation issues such as phone numbers, education grades, employment statuses, and marital statuses. Additionally, the error handling logic in the errorHandler function has been updated to accommodate these new messages, replacing a switch statement with if-else conditions for improved specificity in error reporting.

Changes

File Change Summary
public/locales/en/errors.json Added new error messages for phone number, education grade, employment status, marital status, and generic errors. Minor formatting change to existing message.
public/locales/fr/errors.json Added new error messages in French for phone number, education grade, employment status, marital status, and generic errors.
public/locales/hi/errors.json Added new error messages in Hindi for phone number, education grade, employment status, marital status, and generic errors.
public/locales/sp/errors.json Added new error messages in Spanish for phone number, education grade, employment status, marital status, and generic errors.
public/locales/zh/errors.json Added new error messages in Chinese for phone number, education grade, employment status, marital status, and generic errors.
src/utils/errorHandler.tsx Updated error handling logic to use if-else statements for new error messages related to validation and server responses.
src/utils/errorHandler.test.tsx Added new test cases for the errorHandler function to verify behavior with various error messages.

Assessment against linked issues

Objective Addressed Explanation
Simplify error messages for user at Talawa User Portal (#2464)

Possibly related PRs

  • [Translations] Errors and Success #2078: This PR updates the errors.json file to include new error messages related to input validation, which directly relates to the changes made in the main PR that also adds new error messages for user input validation issues.

🐰 "In the fields where users roam,
New messages guide them home.
With clarity in every line,
Input errors now align.
A hop, a skip, a joyful cheer,
For friendly errors, we hold dear!" 🐇✨


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 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

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

🧹 Outside diff range and nitpick comments (7)
public/locales/hi/errors.json (2)

15-15: Consider enhancing the 400 error message with more specific guidance

While the message is user-friendly, consider adding specific examples of what to check (e.g., "जैसे फ़ोन नंबर, शिक्षा आदि" - such as phone number, education, etc.) to make it even more helpful.

- "error400": "आपकी जानकारी सहेजी नहीं जा सकी। कृपया अपनी प्रविष्टियों की जांच करें और पुनः प्रयास करें।",
+ "error400": "आपकी जानकारी सहेजी नहीं जा सकी। कृपया अपनी प्रविष्टियों (जैसे फ़ोन नंबर, शिक्षा आदि) की जांच करें और पुनः प्रयास करें।",

16-16: Consider adding support contact information to default error message

The default error message could be more helpful by including information about contacting support if the error persists.

- "defaultError": "कुछ गलत हो गया है। कृपया बाद में दोबारा प्रयास करें।"
+ "defaultError": "कुछ गलत हो गया है। कृपया बाद में दोबारा प्रयास करें। यदि समस्या बनी रहती है, तो कृपया सहायता से संपर्क करें।"
public/locales/fr/errors.json (1)

11-14: Add periods for consistency with existing messages.

The new validation messages should maintain consistency with the existing messages in the file that end with periods.

Apply this diff:

-  "invalidPhoneNumber": "Veuillez entrer un numéro de téléphone valide",
-  "invalidEducationGrade": "Veuillez sélectionner un niveau d'études valide",
-  "invalidEmploymentStatus": "Veuillez sélectionner un statut d'emploi valide",
-  "invalidMaritalStatus": "Veuillez sélectionner un état matrimonial valide",
+  "invalidPhoneNumber": "Veuillez entrer un numéro de téléphone valide.",
+  "invalidEducationGrade": "Veuillez sélectionner un niveau d'études valide.",
+  "invalidEmploymentStatus": "Veuillez sélectionner un statut d'emploi valide.",
+  "invalidMaritalStatus": "Veuillez sélectionner un état matrimonial valide.",
public/locales/en/errors.json (1)

11-14: Messages are clear and consistent, consider adding validation requirements.

The validation messages are user-friendly and follow a consistent structure. However, they could be more helpful by including specific requirements.

Consider enhancing the messages with specific requirements:

-  "invalidPhoneNumber": "Please enter a valid phone number",
+  "invalidPhoneNumber": "Please enter a valid phone number (e.g., +1-234-567-8900)",
-  "invalidEducationGrade": "Please select a valid education grade",
+  "invalidEducationGrade": "Please select an education grade from the provided options",
-  "invalidEmploymentStatus": "Please select a valid employment status",
+  "invalidEmploymentStatus": "Please select an employment status from the provided options",
-  "invalidMaritalStatus": "Please select a valid marital status",
+  "invalidMaritalStatus": "Please select a marital status from the provided options"
src/utils/errorHandler.tsx (3)

13-13: Add type narrowing for better type safety

While the error message extraction works, consider adding explicit type narrowing for better type safety.

-const errorMessage = error.message;
+const errorMessage = error.message || 'Unknown error occurred';

26-27: Enhance default error handling with more context

The current default error handling could be more informative for debugging purposes.

Consider enhancing the default error handling:

-    } else {
-      toast.error(tErrors('defaultError'));
+    } else {
+      // Log the unexpected error for debugging
+      console.debug('[ErrorHandler] Unhandled error:', errorMessage);
+      toast.error(tErrors('defaultError', { context: errorMessage.substring(0, 100) }));

Line range hint 1-31: Consider enhancing error message presentation

While the current implementation improves error message clarity, consider these architectural improvements:

  1. Group related validation errors (e.g., all profile field validations) to show them together
  2. Implement progressive error display to show one error at a time
  3. Add error recovery suggestions where applicable

Example implementation approach:

interface ValidationError {
  field: string;
  message: string;
  suggestion?: string;
}

interface ErrorGroup {
  type: 'validation' | 'network' | 'server';
  errors: ValidationError[];
}

// Group errors by type and show them appropriately
const showErrors = (errorGroup: ErrorGroup, tErrors: TFunction) => {
  switch(errorGroup.type) {
    case 'validation':
      // Show first error, with option to see more
      const [firstError, ...rest] = errorGroup.errors;
      toast.error(tErrors(firstError.message), {
        onClick: () => rest.length && showMoreErrors(rest)
      });
      break;
    // ... handle other error types
  }
};
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c80b44f and 9866e56.

📒 Files selected for processing (6)
  • public/locales/en/errors.json (1 hunks)
  • public/locales/fr/errors.json (1 hunks)
  • public/locales/hi/errors.json (1 hunks)
  • public/locales/sp/errors.json (1 hunks)
  • public/locales/zh/errors.json (1 hunks)
  • src/utils/errorHandler.tsx (1 hunks)
🔇 Additional comments (8)
public/locales/zh/errors.json (2)

10-10: LGTM: Formatting is consistent

The formatting adjustment maintains consistency with the new entries while preserving the existing translation.


11-14: Validation messages are clear and consistent

The new validation messages are well-structured and use appropriate Chinese phrases. They maintain consistency by using "请选择" (please select) pattern throughout.

Let's verify consistency across all locale files:

✅ Verification successful

Let me try a different approach to verify the content of these files.


Validation messages are consistent across all locales

The validation messages for phone number, education grade, employment status, and marital status are properly translated and maintain consistent meaning across all language files (zh, sp, en, fr, hi). Each translation:

  • Uses appropriate language-specific phrases for "please select/enter"
  • Maintains the same validation context
  • Follows similar grammatical structure within each language
  • Conveys equivalent meaning across all locales
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistency of validation messages across all locales
# Expected: Similar structure and equivalent meanings across languages

# Find all error.json files and show the validation messages
fd 'errors.json' public/locales -x echo "=== {} ===" \; cat {} \; echo

Length of output: 462


Script:

#!/bin/bash
# Check content of each errors.json file individually
echo "=== Chinese (zh) ==="
cat public/locales/zh/errors.json
echo -e "\n=== Spanish (sp) ==="
cat public/locales/sp/errors.json
echo -e "\n=== English (en) ==="
cat public/locales/en/errors.json
echo -e "\n=== French (fr) ==="
cat public/locales/fr/errors.json
echo -e "\n=== Hindi (hi) ==="
cat public/locales/hi/errors.json

Length of output: 4906

public/locales/hi/errors.json (2)

11-14: Well-structured validation messages!

The validation messages are clear, polite, and actionable. They follow good UX practices by:

  • Using consistent structure starting with "कृपया" (please)
  • Clearly indicating what action the user needs to take
  • Maintaining a helpful tone

11-16: Verify consistency across language files

Let's ensure these new error messages are consistently implemented across all language files.

✅ Verification successful

All error messages are consistently implemented across language files

All the required error message keys (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus, error400, defaultError) are present and properly translated in all language files (en, fr, sp, zh). Each key has appropriate translations that convey the same meaning across languages.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all new error keys exist in other language files
# Expected: All keys should be present in en, fr, sp, and zh locale files

for key in "invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus" "error400" "defaultError"; do
  echo "Checking key: $key"
  for lang in "en" "fr" "sp" "zh"; do
    if [ -f "public/locales/$lang/errors.json" ]; then
      echo "$lang:" $(jq ".$key" "public/locales/$lang/errors.json")
    fi
  done
done

Length of output: 7181

public/locales/en/errors.json (1)

10-10: LGTM!

The formatting adjustment maintains consistency while preserving the existing template variable usage.

public/locales/sp/errors.json (3)

11-14: LGTM! Well-structured validation messages

The new validation messages are clear, consistent, and follow good Spanish localization practices. They effectively guide users on how to correct their input.


16-16: LGTM! Clear and helpful default error message

The default error message is well-written, providing clear information without technical jargon and suggesting an appropriate action.


11-16: Verify translations across all language files

Let's ensure these new error messages are consistently implemented across all language files (en, fr, hi, zh).

✅ Verification successful

All error messages are properly translated across language files

The verification confirms that all the required error message keys (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus, error400, defaultError) are present in all language files (en, fr, hi, zh). Each key returned true for every language, indicating complete coverage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all new error keys exist in other language files
# and verify their structure matches the Spanish version

# Define the required keys
KEYS=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus" "error400" "defaultError")

# Check each language file
for lang in en fr hi zh; do
  echo "Checking $lang translations..."
  if [ -f "public/locales/$lang/errors.json" ]; then
    for key in "${KEYS[@]}"; do
      jq "has(\"$key\")" "public/locales/$lang/errors.json"
    done
  else
    echo "Warning: Missing localization file for $lang"
  fi
done

Length of output: 2896

public/locales/zh/errors.json Outdated Show resolved Hide resolved
public/locales/fr/errors.json Outdated Show resolved Hide resolved
public/locales/fr/errors.json Outdated Show resolved Hide resolved
public/locales/en/errors.json Outdated Show resolved Hide resolved
public/locales/sp/errors.json Outdated Show resolved Hide resolved
src/utils/errorHandler.tsx Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 28, 2024
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
public/locales/sp/errors.json (1)

16-16: Consider adding support contact information

The default error message is clear and appropriate. Consider adding information about how users can get support if the error persists.

-  "defaultError": "Algo salió mal. Inténtalo de nuevo más tarde."
+  "defaultError": "Algo salió mal. Inténtalo de nuevo más tarde o contacta a soporte si el problema persiste."
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9866e56 and 12bf242.

📒 Files selected for processing (3)
  • public/locales/fr/errors.json (1 hunks)
  • public/locales/sp/errors.json (1 hunks)
  • public/locales/zh/errors.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • public/locales/fr/errors.json
  • public/locales/zh/errors.json
🔇 Additional comments (3)
public/locales/sp/errors.json (3)

11-14: LGTM! Well-structured validation messages

The validation messages are clear, consistent, and user-friendly. They follow a good pattern of politely instructing users what action to take.


15-15: LGTM! User-friendly error message

The HTTP 400 error message has been appropriately simplified, focusing on what users need to do rather than technical details.


11-16: Verify translations across all language files

Let's ensure these new error messages are consistently implemented across all language files.

✅ Verification successful

Let me get more detailed information about the content of these error messages across all language files.


All error messages are properly implemented across language files

The verification shows that all six error messages (invalidPhoneNumber, invalidEducationGrade, invalidEmploymentStatus, invalidMaritalStatus, error400, defaultError) are present and properly translated in all language files (en, fr, hi, sp, zh). Each translation maintains consistent meaning while being culturally appropriate for the target language.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if all language files contain the new error messages

# Define the required keys
keys=("invalidPhoneNumber" "invalidEducationGrade" "invalidEmploymentStatus" "invalidMaritalStatus" "error400" "defaultError")

# Find all error.json files
fd 'errors.json' public/locales | while read -r file; do
  echo "Checking $file..."
  for key in "${keys[@]}"; do
    if ! grep -q "\"$key\":" "$file"; then
      echo "Missing key: $key in $file"
    fi
  done
done

Length of output: 3385


Script:

#!/bin/bash
# Get the actual content of all error messages from each language file
for file in $(fd 'errors.json' public/locales); do
  echo "=== Content of $file ==="
  cat "$file"
  echo -e "\n"
done

Length of output: 5556

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 28, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 29, 2024
Copy link

codecov bot commented Nov 29, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 83.80%. Comparing base (c80b44f) to head (710103b).
Report is 2 commits behind head on develop-postgres.

Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #2500       +/-   ##
=====================================================
- Coverage             95.82%   83.80%   -12.02%     
=====================================================
  Files                   295      312       +17     
  Lines                  7037     8127     +1090     
  Branches               1520     1837      +317     
=====================================================
+ Hits                   6743     6811       +68     
- Misses                   98     1177     +1079     
+ Partials                196      139       -57     

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

Copy link

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

🧹 Outside diff range and nitpick comments (2)
src/utils/errorHandler.test.tsx (2)

24-29: Improve test description and error message matching

The test structure is good, but consider these improvements:

  1. Simplify the test description to "should handle invalid phone number errors"
  2. Consider using exact string matching instead of substring matching to prevent false positives
-  it('should call toast.error with the correct message if error message contains this substring "Value is not a valid phone number"', () => {
+  it('should handle invalid phone number errors', () => {

54-59: Enhance HTTP 400 error test coverage

The test covers basic 400 error handling, but consider adding tests for:

  1. Different 400 error scenarios (e.g., validation errors, bad request format)
  2. Translation of error messages in different locales

Example addition:

test.each([
  ['en', 'Bad Request'],
  ['fr', 'Requête Incorrecte'],
  ['hi', 'अमान्य अनुरोध'],
])('should handle 400 error in %s locale', (locale, expected) => {
  const error = new Error('Server responded with status code 400');
  const tLocale = (key: string) => expected;
  errorHandler(tLocale, error);
  expect(toast.error).toHaveBeenCalledWith(expected);
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between de093f7 and 557eafb.

📒 Files selected for processing (1)
  • src/utils/errorHandler.test.tsx (1 hunks)
🔇 Additional comments (1)
src/utils/errorHandler.test.tsx (1)

Line range hint 1-85: Consider adding comprehensive test coverage

While the current tests cover the basic scenarios, consider adding:

  1. Edge cases for each validation type (e.g., empty strings, special characters)
  2. Tests for error message variations and partial matches
  3. Integration tests with the actual translation system

Let's verify the current test coverage:

src/utils/errorHandler.test.tsx Outdated Show resolved Hide resolved
Copy link

@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

🧹 Outside diff range and nitpick comments (1)
src/utils/errorHandler.test.tsx (1)

41-46: Consider adding more specific 400 error test cases.

While this test covers the basic 400 error scenario, consider adding test cases for specific validation errors that might trigger a 400 response (e.g., missing required fields, invalid data formats).

Example addition:

test.each([
  ['Missing required field', 'error400MissingField'],
  ['Invalid data format', 'error400InvalidFormat'],
  ['Validation failed', 'error400ValidationFailed']
])('should handle specific 400 error: %s', (errorMessage, expectedKey) => {
  const error = new Error(`Server responded with status code 400: ${errorMessage}`);
  errorHandler(t, error);
  expect(toast.error).toHaveBeenCalledWith(tErrors(expectedKey));
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 57d0cf1 and 44d1174.

📒 Files selected for processing (1)
  • src/utils/errorHandler.test.tsx (1 hunks)
🔇 Additional comments (2)
src/utils/errorHandler.test.tsx (2)

24-29: LGTM! Clear and focused test case.

The test case effectively validates the error handling for invalid phone numbers, following testing best practices with clear setup and assertions.


31-39: Excellent use of parameterized testing!

The implementation effectively reduces code duplication while maintaining clarity, exactly as suggested in the previous review.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 29, 2024
@palisadoes
Copy link
Contributor

Please fix the failing tests. Our test code coverage system will fail if any of these conditions occur:

  1. The overall code coverage drops below the target threshold of the repository
  2. Any file in the pull request has code coverage levels below the repository threshold
  3. The code does not comply with our linting check or other related formatting requirements

We do this to ensure the overall reliability of the code base is maintained. This is a prerequisite for getting your PR approved. Assigned reviewers regularly review the PR queue and tend to focus on PRs that are passing.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 2, 2024
@bandhan-majumder
Copy link
Author

bandhan-majumder commented Dec 2, 2024

Tests should be passing now. Added a screenshot of passing all the tests.

Copy link

@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

🧹 Outside diff range and nitpick comments (3)
src/utils/errorHandler.test.tsx (3)

14-22: Remove debug logging from test utility function

The console.log statement in the tErrors function appears to be debugging code. It's best to keep test utilities clean and free of debug statements.

  const tErrors: TFunction = (
    key: string,
    options?: Record<string, unknown>,
  ) => {
-   if (options) {
-     console.log(`options are passed, but the function returns only ${key}`);
-   }
    return key;
  };

35-40: Remove debug logging from test

The test looks good but contains an unnecessary console.log statement that should be removed.

  it('should call toast.error with the correct message if error message contains this substring "Value is not a valid phone number"', () => {
    const error = new Error('This value is not a valid phone number');
    errorHandler(t, error);
-   console.log(toast.error);
    expect(toast.error).toHaveBeenCalledWith(tErrors('invalidPhoneNumber'));
  });

52-57: Remove extra blank line for consistency

The test logic is good, but there's an unnecessary blank line before the expect statement that should be removed for consistency with other test cases.

  it('should call toast.error with the correct message if error message contains this substring "status code 400"', () => {
    const error = new Error('Server responded with status code 400');
    errorHandler(t, error);
-
    expect(toast.error).toHaveBeenCalledWith(tErrors('error400'));
  });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 06a9a64 and 710103b.

📒 Files selected for processing (2)
  • src/utils/errorHandler.test.tsx (1 hunks)
  • src/utils/errorHandler.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/utils/errorHandler.tsx
🔇 Additional comments (2)
src/utils/errorHandler.test.tsx (2)

24-26: LGTM! Good test hygiene

Adding jest.clearAllMocks() in beforeEach ensures proper test isolation.


42-50: LGTM! Excellent use of parameterized tests

Great implementation using test.each to reduce code duplication and improve maintainability.

@bandhan-majumder
Copy link
Author

bandhan-majumder commented Dec 2, 2024

My code changes are totally covered. Still the coverage is decreasing (maybe because of previous commits).Please let me know if it needs to be updated anywhere.

image

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