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/OrganizationVenues from Jest to Vitest #2665

Merged

Conversation

im-vedant
Copy link
Contributor

@im-vedant im-vedant commented Dec 14, 2024

What kind of change does this PR introduce?

This PR migrates the test cases in src/screens/OrganizationVenues/OrganizationVenues.test.tsx from Jest to Vitest, ensuring compatibility with Vitest .

✅ Replace Jest-specific functions and mocks with Vitest equivalents
✅ Ensure all tests in src/screens/OrganizationVenues/OrganizationVenues.test.tsx pass after migration using npm run test:vitest
✅ Maintain the test coverage for the file as 100% after migration
✅ Upload a video or photo for this specific file coverage is 100% in the PR description

Issue Number:

Fixes #2563

Did you add tests for your changes?

No

ScreenShot
image
Screenshot 2024-12-15 042019

Summary by CodeRabbit

  • Tests
    • Transitioned testing framework from Jest to Vitest across multiple test files.
    • Updated mocking for react-toastify and react-router-dom to align with Vitest.
    • Introduced a comprehensive test suite for the CustomTableCell component, covering rendering, loading, error, and no event found scenarios.
    • Modified assertions in OrganizationScreen tests to check for data-expanded attribute instead of CSS classes.
    • Removed the outdated customTableCell.test.tsx file.

Copy link
Contributor

coderabbitai bot commented Dec 14, 2024

Walkthrough

This pull request focuses on migrating test files from Jest to Vitest across multiple components and screens. The changes primarily involve replacing Jest-specific mocking functions with Vitest equivalents, such as changing jest.mock to vi.mock and jest.fn() to vi.fn(). The test logic and structure remain largely unchanged, with minor adjustments to how component states and mocks are verified.

Changes

File Change Summary
src/screens/OrganizationVenues/OrganizationVenues.spec.tsx Transitioned from Jest to Vitest, updated mocking for react-toastify and global functions.
src/components/MemberDetail/customTableCell.spec.tsx Introduced a comprehensive test suite with multiple test cases; updated mocking for react-toastify.
src/components/OrganizationScreen/OrganizationScreen.spec.tsx Migrated mocking for react-router-dom, updated state validation using data-expanded attribute.
src/components/MemberDetail/customTableCell.test.tsx Deleted file containing Jest tests for CustomTableCell, now replaced by the new Vitest suite.

Assessment against linked issues

Objective Addressed Explanation
Replace Jest-specific functions with Vitest equivalents [#2563]
Ensure tests pass using npm run test:vitest [#2563] Requires full test suite verification.
Maintain 100% test coverage [#2563] Requires coverage report verification.

Possibly related issues

Possibly related PRs

Poem

🐰 Hopping through the test terrain,
Jest to Vitest, a coding refrain!
Mocks transformed with playful glee,
Refactoring tests, setting functions free!
Vitest magic, our code's new friend! 🧪✨


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

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 14, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 14, 2024
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 14, 2024
@Cioppolo14
Copy link
Contributor

@im-vedant Please fix the failed tests.

@im-vedant
Copy link
Contributor Author

im-vedant commented Dec 15, 2024

@palisadoes These tests are failing because of some issue while parsing css. Many people are facing the same issue. It would be better if you create separate issue to fix this issue. I would love to work on this issue.

@palisadoes
Copy link
Contributor

@palisadoes These tests are failing because of some issue while parsing css. Many people are facing the same issue. It would be better if you create separate issue to fix this issue. I would love to work on this issue.

Please fix the issue in this PR.

@im-vedant
Copy link
Contributor Author

Okay. I have started working on this issue.

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 (5)
src/setupTests.ts (2)

Line range hint 1-8: Migration required: Replace Jest-specific imports and configurations

This file still contains Jest-specific code that needs to be migrated to Vitest:

  • Replace @testing-library/jest-dom with @testing-library/jest-dom/vitest
  • Replace jest.fn() with vi.fn()
  • Update jest-preview configuration for Vitest
- import '@testing-library/jest-dom';
+ import '@testing-library/jest-dom/vitest'

- global.fetch = jest.fn();
+ global.fetch = vi.fn();

Line range hint 34-43: Update test preview configuration for Vitest

The jest-preview configuration needs to be updated for Vitest compatibility.

- import { jestPreviewConfigure } from 'jest-preview';
+ import { vitestPreviewConfigure } from 'vitest-preview';

- jestPreviewConfigure({
+ vitestPreviewConfigure({
    autoPreview: true,
  });

- jest.setTimeout(15000);
+ vi.setConfig({ testTimeout: 15000 });
src/components/OrganizationScreen/OrganizationScreen.test.tsx (1)

Line range hint 16-20: Migration required: Update Jest mocks to Vitest syntax

The module mocking needs to be updated to use Vitest:

- jest.mock('react-router-dom', () => ({
-   ...jest.requireActual('react-router-dom'),
+ vi.mock('react-router-dom', () => ({
+   ...vi.importActual('react-router-dom'),
    useParams: () => ({ orgId: mockID }),
    useMatch: () => ({ params: { eventId: 'event123', orgId: '123' } }),
  }));
src/components/MemberDetail/customTableCell.test.tsx (2)

Line range hint 8-13: Migration required: Update mock implementation to Vitest

Update the react-toastify mock to use Vitest:

- jest.mock('react-toastify', () => ({
+ vi.mock('react-toastify', () => ({
    toast: {
-     success: jest.fn(),
-     error: jest.fn(),
+     success: vi.fn(),
+     error: vi.fn(),
    },
  }));

Line range hint 77-143: Uncomment and fix error handling tests

The commented-out tests for error handling and "no event found" scenarios should be uncommented and updated to work with Vitest. These tests are important for ensuring robust error handling.

Would you like me to help update these tests to work with Vitest? I can provide the corrected implementation that includes:

  1. Proper error handling assertions
  2. Updated toast mock verifications
  3. Improved timeout handling for Vitest
🧹 Nitpick comments (1)
src/setupTests.ts (1)

11-21: Consider a more robust solution for CSS parsing errors

The current approach of suppressing CSS parsing errors is a workaround that might hide potential issues. Consider:

  1. Using a proper CSS loader configuration in Vitest
  2. Mocking CSS imports directly

Example Vitest configuration for handling CSS:

// vitest.config.ts
export default defineConfig({
  test: {
    environment: 'jsdom',
    globals: true,
    setupFiles: ['./src/setupTests.ts'],
    css: {
      modules: {
        classNameStrategy: 'non-scoped'
      }
    }
  }
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9c87ad3 and e32116e.

📒 Files selected for processing (3)
  • src/components/MemberDetail/customTableCell.test.tsx (1 hunks)
  • src/components/OrganizationScreen/OrganizationScreen.test.tsx (1 hunks)
  • src/setupTests.ts (1 hunks)

Copy link

codecov bot commented Dec 16, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 86.39%. Comparing base (139e985) to head (27e8807).
Report is 9 commits behind head on develop-postgres.

Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #2665      +/-   ##
====================================================
+ Coverage             79.58%   86.39%   +6.80%     
====================================================
  Files                   295      312      +17     
  Lines                  7274     8134     +860     
  Branches               1592     1841     +249     
====================================================
+ Hits                   5789     7027    +1238     
+ Misses                 1222      929     -293     
+ Partials                263      178      -85     

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

@im-vedant
Copy link
Contributor Author

@palisadoes I have fixed those failing test.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 16, 2024
@palisadoes
Copy link
Contributor

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Dec 22, 2024

✅ Actions performed

Full review triggered.

@palisadoes
Copy link
Contributor

Please fix the code so that the tests are not commented out. CodeRabbiti.ai mentioned this as part of its analysis. We need the quality of the code base to improve. Thanks.

You can find 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 (3)
src/components/MemberDetail/customTableCell.spec.tsx (3)

15-49: Consider improving mock data maintainability

While the mock data is well-structured, consider these improvements:

  1. Extract test IDs as constants for reusability
  2. Use Date objects for date fields instead of strings
+const TEST_IDS = {
+  EVENT: 'event123',
+  RECURRING_EVENT: 'recurringEvent123',
+  ORGANIZATION: 'org456',
+};
+
+const TEST_DATES = {
+  START: new Date('2023-05-01'),
+  END: new Date('2023-05-02'),
+};
+
 const mocks = [
   {
     request: {
       query: EVENT_DETAILS,
-      variables: { id: 'event123' },
+      variables: { id: TEST_IDS.EVENT },
     },
     result: {
       data: {
         event: {
-          _id: 'event123',
+          _id: TEST_IDS.EVENT,
           title: 'Test Event',
           description: 'This is a test event description',
-          startDate: '2023-05-01',
-          endDate: '2023-05-02',
+          startDate: TEST_DATES.START.toISOString().split('T')[0],
+          endDate: TEST_DATES.END.toISOString().split('T')[0],

99-127: Consider enhancing error state verification

The error test could be more robust by:

  1. Verifying the exact error message matches the component
  2. Testing different types of GraphQL errors
 it('displays error state', async () => {
+  const errorMessage = 'Network error occurred';
   const errorMock = [
     {
       request: {
         query: EVENT_DETAILS,
         variables: { id: 'event123' },
       },
-      error: new Error('An error occurred'),
+      error: new Error(errorMessage),
     },
   ];

   render(
     <MockedProvider mocks={errorMock} addTypename={false}>
       <table>
         <tbody>
           <CustomTableCell eventId="event123" />
         </tbody>
       </table>
     </MockedProvider>,
   );

   await waitFor(() => {
     expect(
       screen.getByText(
         'Unable to load event details. Please try again later.',
       ),
     ).toBeInTheDocument();
+    // Verify toast error was called with the correct message
+    expect(toast.error).toHaveBeenCalledWith(
+      expect.stringContaining(errorMessage)
+    );
   });
 });

51-160: Consider adding test cases for edge scenarios

The test suite would benefit from additional test cases:

  1. Date formatting for different timezones
  2. Very long event titles
  3. Missing optional fields

Example test case for date formatting:

it('handles different timezones correctly', async () => {
  const datesMock = {
    ...mocks[0],
    result: {
      data: {
        event: {
          ...mocks[0].result.data.event,
          startDate: '2023-12-31',
          endDate: '2024-01-01',
        }
      }
    }
  };

  render(
    <MockedProvider mocks={[datesMock]} addTypename={false}>
      <BrowserRouter>
        <table>
          <tbody>
            <CustomTableCell eventId="event123" />
          </tbody>
        </table>
      </BrowserRouter>
    </MockedProvider>,
  );

  await waitFor(() => screen.getByTestId('custom-row'));
  
  // Verify date appears correctly for different locales/timezones
  expect(screen.getByText(/December 31, 2023/)).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 4b41c47 and 1d577df.

📒 Files selected for processing (1)
  • src/components/MemberDetail/customTableCell.spec.tsx (1 hunks)
🔇 Additional comments (3)
src/components/MemberDetail/customTableCell.spec.tsx (3)

1-14: LGTM! Clean setup of imports and mocks

The imports are well-organized and the toast mock is properly implemented using Vitest's mocking functionality.


51-83: LGTM! Well-structured main test case

The main test case thoroughly verifies the component's rendering and data display.


85-98: LGTM! Loading state test

Good coverage of the loading state scenario.

@im-vedant
Copy link
Contributor Author

@coderabbit.ai full review

Copy link
Contributor

coderabbitai bot commented Dec 22, 2024

@im-vedant: Understood. I will perform a full review.

✅ Actions performed

Full review triggered.

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/OrganizationVenues/OrganizationVenues.spec.tsx (1)

285-289: Consider moving the router mock outside beforeAll

While the migration to Vitest is correct, consider moving the react-router-dom mock outside the test blocks for better maintainability. This would also prevent potential issues with mock timing.

-  beforeAll(() => {
-    vi.doMock('react-router-dom', async () => ({
-      ...(await vi.importActual('react-router-dom')),
-      useParams: () => ({ orgId: 'orgId' }),
-    }));
-  });
-
-  afterAll(() => {
-    vi.clearAllMocks();
-  });
+vi.mock('react-router-dom', async () => ({
+  ...(await vi.importActual('react-router-dom')),
+  useParams: () => ({ orgId: 'orgId' }),
+}));

Also applies to: 293-293, 324-326, 331-331

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 139e985 and 27e8807.

📒 Files selected for processing (4)
  • src/components/MemberDetail/customTableCell.spec.tsx (1 hunks)
  • src/components/MemberDetail/customTableCell.test.tsx (0 hunks)
  • src/components/OrganizationScreen/OrganizationScreen.spec.tsx (1 hunks)
  • src/screens/OrganizationVenues/OrganizationVenues.spec.tsx (5 hunks)
💤 Files with no reviewable changes (1)
  • src/components/MemberDetail/customTableCell.test.tsx
🧰 Additional context used
📓 Learnings (2)
src/screens/OrganizationVenues/OrganizationVenues.spec.tsx (1)
Learnt from: bitbard3
PR: PalisadoesFoundation/talawa-admin#2588
File: src/components/ChangeLanguageDropdown/ChangeLanguageDropdown.spec.tsx:145-155
Timestamp: 2024-12-02T04:20:11.745Z
Learning: In PRs focused solely on refactoring test cases from Jest to Vitest, avoid suggesting optimizations or changes outside the migration scope.
src/components/OrganizationScreen/OrganizationScreen.spec.tsx (1)
Learnt from: bitbard3
PR: PalisadoesFoundation/talawa-admin#2588
File: src/components/ChangeLanguageDropdown/ChangeLanguageDropdown.spec.tsx:145-155
Timestamp: 2024-12-02T04:20:11.745Z
Learning: In PRs focused solely on refactoring test cases from Jest to Vitest, avoid suggesting optimizations or changes outside the migration scope.
🔇 Additional comments (3)
src/components/OrganizationScreen/OrganizationScreen.spec.tsx (1)

13-13: LGTM! Correct migration to Vitest

The migration from Jest to Vitest is implemented correctly, using the recommended async/await pattern for mocking modules.

Also applies to: 15-19

src/components/MemberDetail/customTableCell.spec.tsx (1)

7-13: LGTM! Proper Vitest mock implementation

The migration to Vitest is implemented correctly, with proper mocking of the react-toastify module using vi.fn().

src/screens/OrganizationVenues/OrganizationVenues.spec.tsx (1)

253-259: LGTM! Correct toast mock implementation

The migration of react-toastify mock to Vitest is implemented correctly.

@im-vedant
Copy link
Contributor Author

@palisadoes I have removed the commented code, but still CodeRabbit.ai is not approving my changes.

@palisadoes palisadoes merged commit d5a790d into PalisadoesFoundation:develop-postgres Dec 22, 2024
13 checks passed
@palisadoes
Copy link
Contributor

I merged as an exception

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