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

Added vitest for VolunteerContainer #2693

Conversation

NishantSinghhhhh
Copy link
Contributor

@NishantSinghhhhh NishantSinghhhhh commented Dec 20, 2024

PR Title: Refactor VolunteerContainer Component Tests: Migrate from Jest to Vitest
Issue Number:
Fixes: #2548

Did you add tests for your changes?
Yes

Snapshots/Videos:

Screencast.from.2024-12-21.01-57-16.webm

Summary:
This PR refactors the test suite for the VolunteerContainer component by migrating from Jest to Vitest, in alignment with the project's updated testing framework. The following changes were made:

Updated the testing configuration to be compatible with Vitest.
Refactored all test files related to VolunteerContainer to use Vitest's syntax and features.
Consolidated mock definitions to reduce redundancy across test cases for improved maintainability.

Summary by CodeRabbit

  • Tests
    • Updated unit tests for the VolunteerContainer component to enhance test structure and parameter handling.
    • Transitioned testing framework from jest to vitest.
    • Improved mocking of route parameters and asynchronous handling in test cases.
    • Added data-testid attribute to the title span element in the VolunteerContainer for better testability.

Signed-off-by: NishantSinghhhhh <[email protected]>
Copy link
Contributor

coderabbitai bot commented Dec 20, 2024

Walkthrough

This pull request focuses on refactoring the unit tests for the VolunteerContainer component from Jest to Vitest. The changes include transitioning to the Vitest testing framework, updating mocking strategies, modifying route parameter handling, and improving test asynchronous behavior. The modifications aim to align the test suite with Vitest's syntax and features while maintaining the existing test coverage and functionality.

Changes

File Change Summary
src/screens/EventVolunteers/VolunteerContainer.spec.tsx - Replaced Jest with Vitest testing framework
- Updated renderVolunteerContainer function to accept initialPath
- Added mocked useParams function
- Modified route path from /event/:orgId/:eventId to /org/:orgId/event/:eventId
- Updated test cases to use vi.clearAllMocks() and waitFor for async handling
src/screens/EventVolunteers/VolunteerContainer.tsx - Added data-testid="dataTypeTitle" to the title span element for improved testability

Assessment against linked issues

Objective Addressed Explanation
Replace Jest-specific functions with Vitest equivalents [#2548]
Ensure tests pass using npm run test:vitest [#2548] Actual test run not confirmed in the PR
Maintain 100% test coverage [#2548] Coverage verification not shown

Possibly related issues

Possibly related PRs

Suggested reviewers

  • varshith257
  • pranshugupta54

Poem

🐰 A test migration tale, oh so bright,
From Jest to Vitest, we take flight!
Mocks cleared, routes rewritten with care,
Async events dance without despair.
Code evolves, testing takes new height! 🧪


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

27-35: Consider adding TypeScript types to the mocked useParams

The mock setup is well-implemented using Vitest's async mocking capabilities. However, consider adding type safety to the mocked function.

-const mockedUseParams = vi.fn();
+const mockedUseParams = vi.fn<() => { orgId?: string; eventId?: string }>();

79-96: Enhance toggle screens test with specific assertions

While the async handling is improved, the test could be more robust by verifying the state changes after each radio button click.

 it('Testing Volunteer Container Screen -> Toggle screens', async () => {
   mockedUseParams.mockReturnValue({ orgId: 'orgId', eventId: 'eventId' });

   renderVolunteerContainer();

   const groupRadio = await screen.findByTestId('groupsRadio');
   const requestsRadio = await screen.findByTestId('requestsRadio');
   const individualRadio = await screen.findByTestId('individualRadio');

   expect(groupRadio).toBeInTheDocument();
   expect(requestsRadio).toBeInTheDocument();
   expect(individualRadio).toBeInTheDocument();

   await waitFor(async () => {
     await userEvent.click(groupRadio);
+    expect(groupRadio).toBeChecked();
+    expect(requestsRadio).not.toBeChecked();
+    expect(individualRadio).not.toBeChecked();
+
     await userEvent.click(requestsRadio);
+    expect(groupRadio).not.toBeChecked();
+    expect(requestsRadio).toBeChecked();
+    expect(individualRadio).not.toBeChecked();
+
     await userEvent.click(individualRadio);
+    expect(groupRadio).not.toBeChecked();
+    expect(requestsRadio).not.toBeChecked();
+    expect(individualRadio).toBeChecked();
   });
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 371327e and b26bc6c.

📒 Files selected for processing (1)
  • src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2 hunks)
🔇 Additional comments (3)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (3)

15-16: LGTM: Vitest imports are correctly configured

The necessary testing utilities are properly imported from Vitest, aligning with the PR objective of migrating from Jest.


65-66: LGTM: Proper test cleanup implemented

The beforeEach hook correctly clears all mocks between tests, preventing any interference between test cases.


37-39: Verify the updated route path pattern across the application

The route path has been changed from /event/:orgId/:eventId to /org/:orgId/event/:eventId. This structural change needs verification.

Also applies to: 42-42, 48-48

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 20, 2024
@NishantSinghhhhh
Copy link
Contributor Author

NishantSinghhhhh commented Dec 21, 2024

@varshith257 ,@pranshugupta54 can you please review this PR

@varshith257
Copy link
Member

@NishantSinghhhhh Can you have a look at the coverage report. Although changes seems fine this needs to be in coverage report

@NishantSinghhhhh
Copy link
Contributor Author

@NishantSinghhhhh Can you have a look at the coverage report. Although changes seems fine this needs to be in coverage report

Okay sure , will commit the changes by evening

Signed-off-by: NishantSinghhhhh <[email protected]>
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/EventVolunteers/VolunteerContainer.spec.tsx (2)

17-24: Enhance documentation with testing strategy details.

While the documentation provides a good overview, consider adding details about:

  • The testing strategy (unit/integration)
  • Key test scenarios covered
  • Mocking approach for dependencies

80-97: Enhance toggle screens test with intermediate assertions.

While the test correctly verifies the presence of radio buttons and handles clicks, consider adding assertions after each click to verify the state changes:

 await waitFor(async () => {
   await userEvent.click(groupRadio);
+  expect(groupRadio).toBeChecked();
+  expect(requestsRadio).not.toBeChecked();
+  expect(individualRadio).not.toBeChecked();
+
   await userEvent.click(requestsRadio);
+  expect(groupRadio).not.toBeChecked();
+  expect(requestsRadio).toBeChecked();
+  expect(individualRadio).not.toBeChecked();
+
   await userEvent.click(individualRadio);
+  expect(groupRadio).not.toBeChecked();
+  expect(requestsRadio).not.toBeChecked();
+  expect(individualRadio).toBeChecked();
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b26bc6c and 0ab49ec.

📒 Files selected for processing (1)
  • src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2 hunks)
🔇 Additional comments (3)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (3)

28-36: LGTM! Well-structured mock implementation.

The mock setup correctly preserves the actual router functionality while allowing custom useParams behavior. Good practice using async vi.importActual.


66-67: LGTM! Good test isolation practice.

Using vi.clearAllMocks() in beforeEach ensures clean mock state for each test.


38-40: Verify the updated route path structure across the application.

The route path has been updated from /event/:orgId/:eventId to /org/:orgId/event/:eventId. Please ensure this change is consistent with:

  1. The main router configuration
  2. Any navigation logic in other components
  3. URL generation in the application

Also applies to: 43-43, 49-49

✅ Verification successful

The route path structure is consistent with the new format

Based on the verification of App.tsx and test files:

  • The main router configuration in App.tsx uses the new path structure /org/:orgId/event/:eventId for event routes
  • The test file VolunteerContainer.spec.tsx correctly uses the new path format /org/orgId/event/eventId in its test setup
  • No instances of the old path structure /event/:orgId/:eventId were found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for route definitions and navigation code using the old path structure
rg -l "\/event\/:[^\/]+\/:[^\/]+" --type tsx --type ts

# Search for potential useNavigate or Link usages with the old path
rg "navigate\(.*?\/event\/|to=.*?\/event\/" --type tsx --type ts

Length of output: 333


Script:

#!/bin/bash
# Search for route definitions and navigation code using both old and new path structures
rg "(/event/|/org/.+?/event/)" --type tsx --type ts -l

# Search for specific route-related code
rg "(useNavigate|Link).+?(/event/|/org/.+?/event/)" --type tsx --type ts

# Search for router configuration files
fd -e tsx -e ts "router|routes" --exec rg -l "path.*?(/event/|/org/.+?/event/)" {}

Length of output: 274


Script:

#!/bin/bash
# Search for route definitions and navigation code using both old and new path structures
rg -t ts -t typescript -t tsx "(/event/|/org/.+?/event/)"

# Search for specific route-related code
rg -t ts -t typescript -t tsx "(useNavigate|Link).+(event|org)"

# Search for router configuration files
find . -type f \( -name "*.ts" -o -name "*.tsx" \) -exec grep -l "path.*event" {} \;

Length of output: 1084


Script:

#!/bin/bash
# Check App.tsx for route configuration
cat ./src/App.tsx

# Check specific test files for route patterns
cat ./src/screens/EventVolunteers/VolunteerContainer.spec.tsx
cat ./src/screens/OrganizationDashboard/OrganizationDashboard.spec.tsx

Length of output: 24427

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

codecov bot commented Dec 26, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 88.39%. Comparing base (6997a04) to head (7679f41).
Report is 1 commits behind head on develop-postgres.

Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #2693       +/-   ##
=====================================================
+ Coverage             43.57%   88.39%   +44.82%     
=====================================================
  Files                   299      316       +17     
  Lines                  7420     8271      +851     
  Branches               1623     1812      +189     
=====================================================
+ Hits                   3233     7311     +4078     
+ Misses                 3958      742     -3216     
+ Partials                229      218       -11     

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

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.

See comments

src/screens/EventVolunteers/VolunteerContainer.spec.tsx Outdated Show resolved Hide resolved
src/screens/EventVolunteers/VolunteerContainer.spec.tsx Outdated Show resolved Hide resolved
src/screens/EventVolunteers/VolunteerContainer.spec.tsx Outdated Show resolved Hide resolved
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: 2

🧹 Nitpick comments (1)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (1)

92-96: Separate assertions for each radio button click

The current implementation wraps multiple clicks in a single waitFor, which could mask individual failures. Consider testing each click separately.

-    await waitFor(async () => {
-      await userEvent.click(groupRadio);
-      await userEvent.click(requestsRadio);
-      await userEvent.click(individualRadio);
-    });
+    await userEvent.click(groupRadio);
+    expect(groupRadio).toBeChecked();
+    
+    await userEvent.click(requestsRadio);
+    expect(requestsRadio).toBeChecked();
+    
+    await userEvent.click(individualRadio);
+    expect(individualRadio).toBeChecked();
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ab49ec and 1644c4d.

📒 Files selected for processing (2)
  • src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2 hunks)
  • src/screens/EventVolunteers/VolunteerContainer.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/screens/EventVolunteers/VolunteerContainer.tsx
🔇 Additional comments (2)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2)

27-35: Well-implemented mock using Vitest best practices!

The mock implementation correctly uses vi.importActual to preserve original router functionality while allowing param mocking. This is a clean and maintainable approach.


65-66: Verify if additional setup is needed

While clearing mocks is good practice, the AI summary mentions removed beforeAll and afterAll hooks. Please verify if any critical setup or cleanup code was lost in the migration.

src/screens/EventVolunteers/VolunteerContainer.spec.tsx Outdated Show resolved Hide resolved
src/screens/EventVolunteers/VolunteerContainer.spec.tsx Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 26, 2024
@palisadoes
Copy link
Contributor

@NishantSinghhhhh You haven't addressed my questions

@NishantSinghhhhh
Copy link
Contributor Author

NishantSinghhhhh commented Dec 26, 2024

@NishantSinghhhhh You haven't addressed my questions

I have added all the changes you requested

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

🔭 Outside diff range comments (1)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (1)

Line range hint 77-116: Fix and enhance toggle screens test

The test has several issues that need addressing:

  1. Duplicate render calls (lines 78-94 and line 98)
  2. Missing assertions for state changes after radio button clicks
  3. Inconsistent route paths between tests

Suggested fixes:

  1. Remove the duplicate render call
  2. Add assertions for each view state
  3. Use consistent route paths
 it('Testing Volunteer Container Screen -> Toggle screens', async () => {
-  render(
-    <MockedProvider addTypename={false} link={link1}>
-      <MemoryRouter initialEntries={['/event/']}>
-        <Provider store={store}>
-          <I18nextProvider i18n={i18n}>
-            <Routes>
-              <Route path="/event/" element={<VolunteerContainer />} />
-              <Route
-                path="/"
-                element={<div data-testid="paramsError"></div>}
-              />
-            </Routes>
-          </I18nextProvider>
-        </Provider>
-      </MemoryRouter>
-    </MockedProvider>,
-  );

   mockedUseParams.mockReturnValue({ orgId: 'orgId', eventId: 'eventId' });
   renderVolunteerContainer();

   const groupRadio = await screen.findByTestId('groupsRadio');
   const requestsRadio = await screen.findByTestId('requestsRadio');
   const individualRadio = await screen.findByTestId('individualRadio');

   expect(groupRadio).toBeInTheDocument();
   expect(requestsRadio).toBeInTheDocument();
   expect(individualRadio).toBeInTheDocument();

   await waitFor(async () => {
     await userEvent.click(groupRadio);
+    expect(screen.getByTestId('dataTypeTitle')).toHaveTextContent('Groups');
     await userEvent.click(requestsRadio);
+    expect(screen.getByTestId('dataTypeTitle')).toHaveTextContent('Requests');
     await userEvent.click(individualRadio);
+    expect(screen.getByTestId('dataTypeTitle')).toHaveTextContent('Individual');
   });
-
-  await waitFor(() => {
-    expect(screen.getByTestId('paramsError')).toBeInTheDocument();
-  });
 });
🧹 Nitpick comments (2)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2)

27-35: Add type safety to useParams mock

While the mock setup is correct, consider adding type safety to prevent potential issues.

-const mockedUseParams = vi.fn();
+const mockedUseParams = vi.fn<() => { orgId?: string; eventId?: string; }>();

67-74: Enhance undefined params test cases

Consider adding more edge cases for URL parameters:

  • Invalid orgId/eventId formats
  • Partially defined parameters
it.each([
  [{}],
  [{ orgId: undefined, eventId: 'test' }],
  [{ orgId: 'test', eventId: undefined }],
  [{ orgId: '', eventId: '' }]
])('should handle invalid params: %s', async (params) => {
  mockedUseParams.mockReturnValue(params);
  renderVolunteerContainer();
  await waitFor(() => {
    expect(screen.getByTestId('paramsError')).toBeInTheDocument();
  });
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1644c4d and 7679f41.

📒 Files selected for processing (1)
  • src/screens/EventVolunteers/VolunteerContainer.spec.tsx (3 hunks)
🔇 Additional comments (2)
src/screens/EventVolunteers/VolunteerContainer.spec.tsx (2)

Line range hint 41-52: Fix inconsistent route paths

The route paths in the test setup don't match the actual component routes.

-      <MemoryRouter initialEntries={['/event/orgId/eventId']}>
+      <MemoryRouter initialEntries={['/org/orgId/event/eventId']}>
         <Provider store={store}>
           <LocalizationProvider>
             <I18nextProvider i18n={i18n}>
               <Routes>
                 <Route
-                  path="/event/:orgId/:eventId"
+                  path="/org/:orgId/event/:eventId"
                   element={<VolunteerContainer />}
                 />

15-16: Verify complete Jest to Vitest migration

The Vitest imports look correct. However, let's ensure all Jest-specific code has been migrated.

✅ Verification successful

Based on the search results, I can see that the file src/screens/EventVolunteers/VolunteerContainer.spec.tsx is using Vitest imports correctly, and there are no Jest-specific code patterns in this file. The codebase appears to be in a transitional state where some test files are using Jest while others have been migrated to Vitest.

Migration from Jest to Vitest looks correct for this file

The imports from Vitest are properly done and there are no Jest-specific patterns in the file under review. While other files in the codebase still use Jest, this particular file has been correctly migrated to use Vitest.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining Jest-specific code
rg -i "jest\." 
rg "test\(" 
rg "describe\(" 
rg "expect\(" 
rg "mock\(" 

Length of output: 75085

@palisadoes palisadoes merged commit 1e445f6 into PalisadoesFoundation:develop-postgres Dec 26, 2024
13 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