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

Refactor: src/screens/SubTags from Jest to Vitest #2733

Conversation

PratapRathi
Copy link
Contributor

@PratapRathi PratapRathi commented Dec 23, 2024

What kind of change does this PR introduce?

This PR migrates the test cases in src/screens/SubTags from Jest to Vitest, ensuring compatibility with Vitest and maintaining 100% test coverage.
Added few more test case and some 'istanbul ignore next' comments

Issue Number:
Fixes #2570

Did you add tests for your changes?

Yes

Snapshots/Videos:

Screenshot 2024-12-23 at 21 27 11

If relevant, did you update the documentation?

N/A

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

  • Tests

    • Transitioned the testing framework from Jest to Vitest for the SubTags component.
    • Updated test cases to include error handling for invalid organization IDs.
    • Enhanced flexibility in the test rendering function by adding an initialRoute parameter.
  • Bug Fixes

    • Improved error handling and control flow in the SubTags component, clarifying code comments without changing functionality.

Copy link
Contributor

coderabbitai bot commented Dec 23, 2024

Walkthrough

This pull request focuses on migrating the test suite for the SubTags component from Jest to Vitest. The changes involve updating the testing framework syntax, modifying the renderSubTags function to accept an initial route parameter, and enhancing test coverage. The modifications aim to improve the testing approach while maintaining the existing test logic and component functionality.

Changes

File Change Summary
src/screens/SubTags/SubTags.spec.tsx - Transitioned from Jest to Vitest mocking and testing syntax
- Updated renderSubTags function to include initialRoute parameter
- Added new test cases for error handling
- Replaced Jest mock clearing with Vitest's vi.clearAllMocks()
src/screens/SubTags/SubTags.tsx - Removed unnecessary /* istanbul ignore next */ comments
- Simplified error handling and control flow comments

Assessment against linked issues

Objective Addressed Explanation
Replace Jest-specific functions and mocks with Vitest equivalents (#2570)
Ensure all tests in src/screens/SubTags pass after migration using npm run test:vitest (#2570)
Maintain the test coverage for the file as 100% after migration (#2570)

Possibly related issues

Possibly related PRs

Suggested reviewers

  • palisadoes

📜 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 b2caab3 and cf44483.

📒 Files selected for processing (1)
  • src/screens/SubTags/SubTags.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/screens/SubTags/SubTags.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

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

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/SubTags/SubTags.spec.tsx (2)

82-84: Flexible routing approach
Accepting an 'initialRoute' parameter is a good practice for dynamic test scenarios. This design is commendable for future test expansions.


121-121: Consider removing or keeping vi.clearAllMocks()
Though clearing mocks in afterEach is typical, confirm whether you need additional cleanup steps or if some mocks should persist.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ec91a82 and b2caab3.

📒 Files selected for processing (2)
  • src/screens/SubTags/SubTags.spec.tsx (17 hunks)
  • src/screens/SubTags/SubTags.tsx (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/screens/SubTags/SubTags.tsx (1)
Learnt from: meetulr
PR: PalisadoesFoundation/talawa-admin#2362
File: src/components/TagActions/TagNode.tsx:79-109
Timestamp: 2024-11-12T10:41:04.351Z
Learning: In the `TagNode` component at `src/components/TagActions/TagNode.tsx`, the infinite scroll component efficiently manages the calls to `loadMoreSubTags`, preventing multiple simultaneous requests.
🔇 Additional comments (21)
src/screens/SubTags/SubTags.spec.tsx (19)

24-24: LGTM for Vitest migration
This import effectively transitions from Jest to Vitest, aligning with the new test framework.


48-48: Check for full coverage of toast functionalities
This mock is adequate for basic success/error coverage, but ensure any other toast methods (info, warning) are not needed.


125-125: Test block for component loading
This test thoroughly checks the initial load scenario. Code coverage looks solid.


135-135: Test block for error scenario
Successfully verifies error handling when the subtags query fails.


145-145: Test block for create tag modal flow
Proper test flow to open and close the modal. No issues found.


167-167: Test block for manage tag navigation
Ensures correct route transition. Implementation is correct.


182-182: Test block for sub tag screen navigation
Verifies accurate navigation upon clicking a tag. LGTM.


197-197: Test block for breadcrumbs navigation
Checks that clicking tag in breadcrumbs leads to the correct sub tags screen.


212-212: Breadcrumbs to org tags screen
This confirms the 'allTagsBtn' triggers correct routing.


227-227: Manage current tag
No issues with the logic that directs to manageTag.


242-242: Test block for search functionality
Properly tests searching by name. Good coverage.


263-263: Testing sort order
Successfully verifies switching between latest and oldest sorting.


320-320: Test block for infinite scroll
This effectively ensures loadMoreSubTags is triggered.


349-349: Adding a new sub tag
Verifies successful creation and toast notification. Well covered.


364-367: Ensuring addSubTagSubmitBtn presence
A reliable wait step ensures no race conditions with the UI.


377-401: Invalid OrgID scenario
Appropriately tests error notification on an invalid organization ID.


50-51: Double-check usage of toast mock calls in tests
The success and error mocks look good. Verify their invocation in newly added tests to ensure correctness.

✅ Verification successful

Let me search for the test file and check the toast mock usage.


Let me search for the actual test cases where these mocks might be used.


Toast mocks are properly used and verified in tests
The test file correctly verifies toast mock calls. Specifically:

  • toast.success is verified when adding a new sub tag successfully
  • The test "adds a new sub tag to the current tag" explicitly checks toast.success call with the correct message
  • The test "Adding a subtag with invalid OrgID" appears to test the error case
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Find and show the test file content
rg -A 5 -B 5 "success: vi.fn\(\)" "src/screens/SubTags/SubTags.spec.tsx"

Length of output: 214


Script:

#!/bin/bash
# Search for test cases that might use toast.success or toast.error
rg -A 10 -B 10 "it\(.*" "src/screens/SubTags/SubTags.spec.tsx"

Length of output: 7180


25-25: Confirm that matchers are properly installed
While this import from '@testing-library/jest-dom/vitest' is valid for Vitest environment, verify that all expected matchers (e.g., toBeInTheDocument) remain functional.

✅ Verification successful

Let me verify the functionality of Jest DOM matchers by checking the test files and their usage.


Let me try different commands to verify the Jest DOM setup and usage.


Based on the results, I can now generate the final response:

Jest DOM matchers are properly configured and functional
The codebase shows consistent usage of Jest DOM matchers across multiple test files, with proper configuration in both vitest.setup.ts and setupTests.ts. The import from '@testing-library/jest-dom/vitest' is valid and the extensive test suite demonstrates active usage of matchers like toBeInTheDocument(), toHaveClass(), toHaveAttribute(), etc.

🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# Search for usage of Jest DOM matchers in test files
rg "toBeInTheDocument|toHaveAttribute|toHaveClass|toHaveStyle|toBeVisible|toBeDisabled" -t tsx -t ts --context 2

Length of output: 142


Script:

#!/bin/bash
# Check test setup files for Jest DOM configuration
fd "setup" -e ts -e js -e tsx

Length of output: 133


Script:

#!/bin/bash
# Check package.json for testing dependencies
cat package.json | jq '.dependencies + .devDependencies'

Length of output: 3659


Script:

#!/bin/bash
# Look for other test files using the same import
rg "@testing-library/jest-dom/vitest" -t tsx -t ts

Length of output: 78


Script:

#!/bin/bash
# Search for test files and their content without specifying file extensions
rg "toBeInTheDocument|toHaveAttribute|toHaveClass|toHaveStyle|toBeVisible|toBeDisabled"

Length of output: 65952


Script:

#!/bin/bash
# Check content of test setup files
cat vitest.setup.ts setup.ts src/setupTests.ts

Length of output: 7058


Script:

#!/bin/bash
# Look for jest-dom imports without specifying file extensions
rg "@testing-library/jest-dom"

Length of output: 946


114-115: Ensure partial mocking doesn’t break navigation
Mocking 'react-router-dom' in this manner might introduce unintended side effects if key exports are overridden. Confirm everything still navigates as expected.

✅ Verification successful

Let me analyze the codebase to verify if the partial mocking of 'react-router-dom' could potentially cause issues.

This will help us understand:

  1. How widespread is the mocking of react-router-dom
  2. What specific implementations are used for mocking
  3. Which router features are actually being used in the codebase

Let me modify the search to handle TypeScript files correctly.


Let me try without specifying file types, as ripgrep should handle TypeScript files by default.


Based on the analysis of the codebase, I can now provide a final response regarding the partial mocking of 'react-router-dom' in SubTags.spec.tsx.

Partial mocking implementation is safe and follows best practices
The current implementation using vi.mock('react-router-dom', async () => ({...(await vi.importActual('react-router-dom')),})) is a safe approach as it preserves all original router functionality while allowing specific overrides. The test file doesn't override any navigation-related functions, making it impossible to break navigation behavior.

Reasoning:

  1. The mock implementation properly imports the actual module first using vi.importActual
  2. No navigation-related functions (useNavigate, Link, etc.) are being overridden in the mock
  3. The pattern is consistently used across many test files in the codebase
  4. The file under test (SubTags.tsx) uses standard router hooks (useNavigate, useParams, Link) which remain intact with this mocking approach
🏁 Scripts executed

The following scripts were executed for the analysis:

Error: No shell scripts found


Script:

#!/bin/bash
# First, let's find all test files that mock react-router-dom
rg -l "mock.*react-router-dom" --type ts --type tsx

# Then, let's see the specific mock implementations
rg "mock.*react-router-dom" -B2 -A5 --type ts --type tsx

# Let's also check for router-related imports and usage
rg "from 'react-router-dom'" -B1 -A1 --type ts --type tsx

Length of output: 262


Script:

#!/bin/bash
# Find all test files that mock react-router-dom
rg -l "mock.*react-router-dom" -t typescript

# See the specific mock implementations
rg "mock.*react-router-dom" -B2 -A5 -t typescript

# Check for router-related imports and usage
rg "from 'react-router-dom'" -B1 -A1 -t typescript

# Also check for any navigation-related functions or hooks usage
rg "useNavigate|useLocation|useParams|Link|NavLink|Navigate" -t typescript

Length of output: 374


Script:

#!/bin/bash
# Find all test files that mock react-router-dom
rg -l "mock.*react-router-dom"

# See the specific mock implementations with context
rg "mock.*react-router-dom" -B2 -A5

# Check for router-related imports and usage
rg "from 'react-router-dom'"

# Check for any navigation-related functions or hooks usage
rg "useNavigate|useLocation|useParams|Link|NavLink|Navigate"

Length of output: 65804

src/screens/SubTags/SubTags.tsx (2)

96-97: Clearer coverage approach
Removing the "istanbul ignore" comment enhances transparency in test coverage. The logical check for fetchMoreResult remains intact.


157-157: No changes to functionality
This line simply references subTagsList creation. No concerns or performance bottlenecks identified.

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

codecov bot commented Dec 23, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.16%. Comparing base (ec91a82) to head (cf44483).

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #2733      +/-   ##
===========================================
- Coverage    90.52%   85.16%   -5.36%     
===========================================
  Files          295      312      +17     
  Lines         7249     8125     +876     
  Branches      1591     1783     +192     
===========================================
+ Hits          6562     6920     +358     
- Misses         455     1049     +594     
+ Partials       232      156      -76     

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

@Cioppolo14
Copy link
Contributor

@PratapRathi Please fix the first comment so the issue is automatically closed when the PR is merged. Please fix the failed test.

@PratapRathi
Copy link
Contributor Author

@Cioppolo14 I updated the comment so the Issue will close after merge, and Revert some "istanbul ignore next" comments which I was removed that's why test coverage decreased, now test coverage is almost 95% which is 5% higher than initial jest test, but codecov report is not updated yet.

Current code coverage
Screenshot 2024-12-23 at 21 43 08

Old code coverage in Jest
Screenshot 2024-12-23 at 21 53 23

@palisadoes
Copy link
Contributor

Please submit your PRs against our develop-postgres branch. This is a temporary requirement as we prepare to migrate our API backend to Postgres.

Also if applicable, make sure your branch name is different from develop-postgres when resubmitting.

Closing.

@palisadoes palisadoes closed this Dec 23, 2024
@PratapRathi PratapRathi deleted the Migrate-src/screens/SubTags-from-Jest-to-Vitest branch December 23, 2024 17:37
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