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

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

Conversation

im-vedant
Copy link

@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

  • New Features

    • Added a data-expanded attribute to the OrganizationScreen component to indicate the state of the drawer.
  • Bug Fixes

    • Enhanced test cases for the CustomTableCell component to dynamically generate event dates for improved flexibility.
    • Updated tests for the OrganizationScreen to verify drawer state using the new data-expanded attribute.
  • Tests

    • Transitioned test files from Jest to Vitest for improved mock handling.
    • Updated mocking for react-toastify in multiple test files to use Vitest.
  • Chores

    • Updated configuration for CSS and LESS module handling in the Jest config.

Copy link

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 and testing functions with their Vitest equivalents. Key modifications include updating test files for OrganizationVenues, OrganizationScreen, MemberDetail, and adjusting the Jest configuration to support CSS module mocking. The overall structure and logic of the tests remain consistent, with only syntactical changes to align with the Vitest testing framework.

Changes

File Change Summary
src/screens/OrganizationVenues/OrganizationVenues.spec.tsx Migrated from Jest to Vitest, replacing jest.mock with vi.mock and updating mocking functions
src/components/OrganizationScreen/OrganizationScreen.tsx Added data-expanded attribute to reflect drawer state
jest.config.js Added CSS module mapping with identity-obj-proxy
src/components/MemberDetail/customTableCell.spec.tsx Updated react-toastify mocking from Jest to Vitest
src/components/OrganizationScreen/OrganizationScreen.spec.tsx Migrated to Vitest, updated router mocking and state verification

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] Needs comprehensive coverage check

Possibly related issues

Possibly related PRs

Suggested labels

refactor

Suggested reviewers

  • palisadoes

Poem

🐰 Hop, hop, through the testing ground,
Jest steps aside, Vitest now found!
Mocks and functions dance anew,
Code leaps forward, tests ring true!
A rabbit's cheer for framework's might! 🧪


📜 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 8aea843 and 650f431.

📒 Files selected for processing (2)
  • src/components/MemberDetail/customTableCell.spec.tsx (2 hunks)
  • src/components/OrganizationScreen/OrganizationScreen.spec.tsx (2 hunks)
🧰 Additional context used
📓 Learnings (1)
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 (4)
src/components/OrganizationScreen/OrganizationScreen.spec.tsx (2)

13-13: LGTM: Jest to Vitest migration changes look correct.

The migration changes follow the correct pattern:

  • Proper import of vi
  • Correct usage of vi.mock with importActual

Also applies to: 15-18


83-86: LGTM: Test assertions updated to match component changes.

The test assertions have been properly updated to check the data-expanded attribute instead of CSS classes, maintaining the test's intent while adapting to component changes.

Also applies to: 92-94

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

7-11: LGTM: Jest to Vitest mock migration looks correct.

The migration changes follow the correct pattern:

  • Proper import of vi
  • Correct usage of vi.mock for react-toastify
  • Appropriate replacement of jest.fn() with vi.fn()

68-77: LGTM: Date assertion updated to be locale-aware.

The test assertion has been improved to use toLocaleDateString with explicit options, making it more robust across different locales while maintaining the test's intent.


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

@im-vedant Please fix the failed tests.

@im-vedant
Copy link
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
Author

Okay. I have started working on this issue.

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 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 83.92%. Comparing base (debe672) to head (650f431).
Report is 5 commits behind head on develop-postgres.

Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #2665      +/-   ##
====================================================
- Coverage             92.23%   83.92%   -8.32%     
====================================================
  Files                   295      312      +17     
  Lines                  7036     8129    +1093     
  Branches               1516     1836     +320     
====================================================
+ Hits                   6490     6822     +332     
- Misses                  342     1158     +816     
+ Partials                204      149      -55     

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

@im-vedant
Copy link
Author

@palisadoes I have fixed those failing test.

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 16, 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 comments (2)
src/components/OrganizationScreen/OrganizationScreen.test.tsx (2)

Line range hint 1-19: Update Jest-specific imports and mocks for Vitest compatibility

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

Apply these changes for Vitest compatibility:

- import 'jest-location-mock';
+ import 'vitest-location-mock';

- jest.mock('react-router-dom', () => ({
-   ...jest.requireActual('react-router-dom'),
+ vi.mock('react-router-dom', () => ({
+   ...vi.importActual('react-router-dom'),

Line range hint 98-106: Maintain consistency in test assertions

While the drawer toggle tests have been updated to use data attributes, the window resize test still relies on class-based assertions. This inconsistency could contribute to the CSS parsing issues mentioned in the PR comments.

Consider updating the window resize test to match the new pattern:

   test('handles window resize', () => {
     renderComponent();
 
     window.innerWidth = 800;
     fireEvent(window, new Event('resize'));
 
-    expect(screen.getByTestId('mainpageright')).toHaveClass(styles.expand);
+    expect(screen.getByTestId('mainpageright')).toHaveAttribute('data-expanded', 'true');
   });

This change would:

  1. Maintain consistency with other tests
  2. Reduce dependency on CSS modules
  3. Help mitigate the CSS parsing issues
🧹 Nitpick comments (1)
src/components/OrganizationScreen/OrganizationScreen.test.tsx (1)

84-87: Update test comments to match new assertion style

The migration to data-attribute assertions is a good improvement, matching our previous recommendations. However, the comments still reference the old class-based checks.

Update the comments to reflect the new assertion style:

-    // Check for contract class after closing
+    // Check for expanded state after closing
     expect(screen.getByTestId('mainpageright')).toHaveAttribute(
       'data-expanded',
       'true',
     );

-    // Check for expand class after opening
+    // Check for expanded state after opening
     expect(screen.getByTestId('mainpageright')).toHaveAttribute(
       'data-expanded',
       'false',
     );

Also applies to: 93-95

📜 Review details

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

📥 Commits

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

📒 Files selected for processing (3)
  • src/components/MemberDetail/customTableCell.test.tsx (1 hunks)
  • src/components/OrganizationScreen/OrganizationScreen.test.tsx (1 hunks)
  • src/components/OrganizationScreen/OrganizationScreen.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/OrganizationScreen/OrganizationScreen.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/MemberDetail/customTableCell.test.tsx

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

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

Please exclude file src/setupTests.ts from the PR. Modifying it is not required for the issue to be resolved.

@palisadoes palisadoes changed the title Code refactor Refactor: src/screens/OrganizationVenues from Jest to Vitest Dec 16, 2024
@im-vedant
Copy link
Author

im-vedant commented Dec 16, 2024

@palisadoes Some jest test were failing because jsdom css parser was not able to parse the stylesheet. Only solution to fix this issue is to ignore that error. That's why I have to edit the setupTest.ts file. You can refer to this jsdom/jsdom#2177 issue for more details.

@palisadoes
Copy link
Contributor

The solution is to fix the parsing of the CSS file, not to ignore errors. Please fix it.

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

🧹 Nitpick comments (1)
jest.config.js (1)

38-38: Fix formatting: Remove leading whitespace

Remove the extra space at the beginning of line 38 to maintain consistent formatting.

-     '\\.(css|less)$': 'identity-obj-proxy',
+    '\\.(css|less)$': 'identity-obj-proxy',
🧰 Tools
🪛 eslint

[error] 38-38: Delete ·

(prettier/prettier)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b9f0830 and 18cc26b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • jest.config.js (1 hunks)
🧰 Additional context used
🪛 eslint
jest.config.js

[error] 38-38: Delete ·

(prettier/prettier)

jest.config.js Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 16, 2024
@im-vedant
Copy link
Author

@palisadoes I fixed the issue by installing identity-obj-proxy, as suggested in the Jest documentation on mocking CSS modules.

@im-vedant im-vedant requested a review from palisadoes December 17, 2024 17:12
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.

Convert the edited *.test.tsx files to vitest as stated in the original issue.

…rc\components\OrganizationScreen\OrganizationScreen.test.tsx from jest to vitest
@@ -35,6 +36,7 @@ export default {
'<rootDir>/src',
],
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
Copy link
Contributor

Choose a reason for hiding this comment

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

Why was this added?

Copy link
Author

Choose a reason for hiding this comment

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

Some jest test were failing because jsdom css parser was not able to parse the stylesheet. I have fixed this issue by installing this package. These line are added to the Jest configuration file to ensure that our Jest test environment can properly handle imported CSS/LESS modules during testing. It is recommended in Jest documentation. https://jestjs.io/docs/webpack#mocking-css-modules

@im-vedant im-vedant requested a review from palisadoes December 17, 2024 21:08
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