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

Improve Code Coverage in src/screens/UserPortal/Chat/Chat.tsx #3163

Merged

Conversation

abbi4code
Copy link
Contributor

@abbi4code abbi4code commented Jan 5, 2025

What kind of change does this PR introduce?
Improved the test code coverage for the screen: src/screens/UserPortal/Chat/Chat.tsx

Issue Number:

Fixes #3037

Did you add tests for your changes?
yes

Snapshots/Videos:
Screenshot from 2025-01-06 00-05-12

Does this PR introduce a breaking change?
yes

Summary by CodeRabbit

  • New Features

    • Improved chat filtering functionality for "all", "unread", and "group" chat types.
  • Tests

    • Added comprehensive test cases for chat filter functionality.
    • Implemented mock data testing for group chat rendering.
  • Refactor

    • Simplified chat component by removing unnecessary state management.
    • Cleaned up modal toggle functions.

Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

Warning

Rate limit exceeded

@abbi4code has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 0486d6d and 92dee41.

📒 Files selected for processing (2)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (3 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (3 hunks)

Walkthrough

The pull request focuses on enhancing the test coverage and simplifying the code structure for the Chat component in the User Portal. Changes include the addition of new test cases for chat filtering functionality in the Chat.spec.tsx file, which now includes tests for group chats. The Chat.tsx component has been streamlined by removing the hideDrawer state and its associated resize logic, as well as eliminating Istanbul ignore comments from modal toggle functions. The function signature for the chat component has been updated to be explicitly exported.

Changes

File Change Summary
src/screens/UserPortal/Chat/Chat.spec.tsx Added new test cases for chat filtering (all, unread, group chats)
src/screens/UserPortal/Chat/Chat.tsx Removed hideDrawer state and related resize logic, updated modal toggle functions, removed Istanbul ignore comments

Assessment against linked issues

Objective Addressed Explanation
Improve Code Coverage [#3037]
Remove Istanbul ignore comments
Ensure 100% code coverage Full coverage verification requires comprehensive review

Possibly related issues

Possibly related PRs

Suggested reviewers

  • disha1202
  • palisadoes

Poem

🐰 A rabbit's tale of code so bright,
Filtering chats with testing might,
Mocks cleared, coverage soaring high,
No resize logic left to sigh,
Chat component, now lean and tight! 🚀


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

github-actions bot commented Jan 5, 2025

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0486d6d and 320753b.

📒 Files selected for processing (2)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (3 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (2 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
src/screens/UserPortal/Chat/Chat.spec.tsx

[error] 4284-4286: Disallow duplicate setup and teardown hooks.

Disallow beforeEach duplicacy inside the describe function.

(lint/suspicious/noDuplicateTestHooks)

🔇 Additional comments (2)
src/screens/UserPortal/Chat/Chat.tsx (2)

140-140: Thank you for removing the Istanbul ignore comment here.

Great job ensuring toggleCreateDirectChatModal is now fully testable, improving overall coverage. Keep verifying that your newly added tests effectively cover both open and close functionalities.


150-150: Nice coverage strategy for toggling Group Chat creation.

Likewise, having toggleCreateGroupChatModal fully covered by tests is beneficial. Ensure that all modal states (open/close) are validated in your test suites.

src/screens/UserPortal/Chat/Chat.spec.tsx Outdated Show resolved Hide resolved
src/screens/UserPortal/Chat/Chat.spec.tsx Outdated Show resolved Hide resolved
src/screens/UserPortal/Chat/Chat.spec.tsx Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 5, 2025
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 (2)
src/screens/UserPortal/Chat/Chat.spec.tsx (2)

32-32: Consider using userEvent instead of fireEvent.

The commented import of userEvent suggests it was considered. userEvent provides more realistic user interaction simulation than fireEvent as it more closely mimics real browser events and user behavior.

-// import userEvent from '@testing-library/user-event';
+import userEvent from '@testing-library/user-event';

Line range hint 4400-4527: Enhance test coverage with additional scenarios.

Consider adding these test cases to improve coverage:

  1. Error handling for failed API calls
  2. Empty chat lists
  3. Network timeout scenarios
  4. Chat filter transitions with loading states
  5. Pagination if applicable

Also consider these improvements:

  1. Create shared test utilities for common operations
  2. Add snapshot tests for consistent UI rendering
  3. Test keyboard navigation
  4. Test accessibility requirements

Would you like me to help create these additional test cases? I can provide implementations for any of these scenarios.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 320753b and 3f9d2c1.

📒 Files selected for processing (2)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (3 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/screens/UserPortal/Chat/Chat.tsx

src/screens/UserPortal/Chat/Chat.spec.tsx Outdated Show resolved Hide resolved
src/screens/UserPortal/Chat/Chat.spec.tsx Outdated Show resolved Hide resolved
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 5, 2025
@abbi4code
Copy link
Contributor Author

@coderabbitai full-review

Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

@abbi4code: Below is a comprehensive review of the entire PR, as requested:


Overall PR Review

Scope & Objective
This PR aims to enhance the test coverage for the Chat component located in src/screens/UserPortal/Chat/Chat.tsx. It addresses issue #3037 and introduces new and revised test cases in Chat.spec.tsx. The changes also streamline the Chat component by removing unused state variables and simplifying the logic.


Detailed Review

1. Chat.tsx

  • Removal of hideDrawer Logic:
    The code that managed window resizing (handleResize) and the hideDrawer state has been removed, simplifying the component. Since there were no observed references to hideDrawer or related logic affecting other parts of the application, this removal appears safe and reduces code complexity.

  • Modal Toggle Functions:
    The Istanbul ignore comments were removed from toggleCreateDirectChatModal and toggleCreateGroupChatModal, which suggests these methods are now fully covered by tests. This is a step forward in ensuring reliable coverage.

  • GraphQL Logic and State Management:
    The main state variables for managing chat data remain unaffected, still focusing on retrieving chats (e.g., all, unread, or group) and toggling the chat creation modal. No major changes were made that might negatively impact existing features.

Recommendation:

  • Verify that removing hideDrawer does not affect any of the responsive designs across the app if you used to rely on that logic.
  • Confirm that all references to hideDrawer are fully removed from other components as well.

2. Chat.spec.tsx

  • New Test Cases:
    The newly introduced tests carefully simulate UI interactions with the chat filters (e.g., clicking on "all", "unread", and "group" filter buttons) and validate the correct rendering of contacts.

  • Coverage Improvements:
    By adding and restructuring the tests, the coverage should increase, especially given that the previously ignored toggleCreateDirectChatModal and toggleCreateGroupChatModal are now tested.

  • Test Clarity:
    The test naming is descriptive, helping future contributors understand the intended behavior quickly. Each test scenario checks the correct fetch call and state updates for different filters.

Recommendation:

  • Ensure each filter scenario is tested for potential edge cases (e.g., when there are no chats, or the user’s data is partially loaded).
  • Continue to incorporate test doubles or appropriate mocking for GraphQL calls to isolate UI logic from network dependencies.

3. Breaking Change Consideration

  • The PR mentions it introduces a breaking change, presumably by removing the hideDrawer logic. If other parts of the larger codebase were relying on that mechanism, it might cause regressions. Double-check usage references outside of this PR and confirm no side effects exist.

Conclusion

This PR improves the test coverage of the Chat component by:

  • Adding more structured tests in Chat.spec.tsx.
  • Removing unused hideDrawer state logic from Chat.tsx.
  • Achieving better clarity and coverage through new, more focused test scenarios.

No severe issues stand out, and the refactoring appears to be beneficial. If you confirm no unintended side effects from removing the hideDrawer logic, this PR should safely meet the project’s goals.

✅ 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 (6)
src/screens/UserPortal/Chat/Chat.tsx (2)

140-140: Ensure consistency in function definitions for better readability.

Using an arrow function for toggling the modal is perfectly fine. However, be consistent across the component. If other toggles or similar functions are declared using function syntax, consider unifying them for codebase uniformity.


150-150: Maintain consistency in arrow function usage.

Same suggestion as above. Consistency fosters easier maintenance and helps new contributors quickly understand your approach to toggling components.

src/screens/UserPortal/Chat/Chat.spec.tsx (4)

32-32: Consider uncommenting userEvent import.

If you’re migrating away from direct fireEvent calls, uncommenting and using userEvent can reduce reliance on multiple async act() blocks and make tests more user-centric.


4285-4349: Reduce multiple act() calls to avoid potential flakiness.

Chaining multiple act() blocks might cause brittle tests. Consider refactoring to use userEvent or consolidated awaits that verify the final UI state, instead of manually using setTimeout.


4350-4400: Add intermediate assertions for better test clarity.

After clicking the “allChat” button, consider asserting the button’s active state before checking the contact cards array length for improved test readability.


4528-4611: Add error condition coverage for group chat fetching.

Everything looks fine for happy-path testing. However, verifying how the component handles a failing or empty group chat response can further boost coverage and reliability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0486d6d and 3f9d2c1.

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

305-305: Looks good!

Rendering the ContactCard with the spread cardProps is clear and straightforward. No issues flagged 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: 1

🧹 Nitpick comments (2)
src/screens/UserPortal/Chat/Chat.spec.tsx (2)

32-32: Uncomment and use userEvent for better interaction testing.

The commented import of userEvent should be uncommented. UserEvent provides a more realistic way to simulate user interactions compared to fireEvent, as it more closely mimics real browser events and their side effects.

-// import userEvent from '@testing-library/user-event';
+import userEvent from '@testing-library/user-event';

4517-4547: Improve test structure while maintaining correct test IDs.

The test correctly uses different test IDs for container and contact elements, but needs structural improvements.

Improve the implementation while maintaining the test ID hierarchy:

 it('should fetch and set group chats when filterType is "group"', async () => {
   setItem('userId', '1');

   render(
     <MockedProvider mocks={mock} addTypename={false}>
       <BrowserRouter>
         <Provider store={store}>
           <I18nextProvider i18n={i18nForTest}>
             <Chat />
           </I18nextProvider>
         </Provider>
       </BrowserRouter>
     </MockedProvider>,
   );

   const groupChatButton = await screen.findByTestId('groupChat');

-  await act(async () => {
-    fireEvent.click(groupChatButton);
-  });
-
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(groupChatButton);
+  await waitFor(() => {
+    expect(groupChatButton).toHaveClass('active');
+  });

   // First verify the container is present
   const container = await screen.findByTestId('contactCardContainer');
   expect(container).toBeInTheDocument();

   // Then verify the contact cards within the container
   const chatContacts = await screen.findAllByTestId('contactContainer');
   expect(chatContacts).toHaveLength(1);
+  
+  // Verify the content of the contact cards
+  expect(chatContacts[0]).toHaveTextContent('Test Group Chat');
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3f9d2c1 and 92dee41.

📒 Files selected for processing (1)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Test Application
  • GitHub Check: Analyse Code With CodeQL (javascript)
🔇 Additional comments (1)
src/screens/UserPortal/Chat/Chat.spec.tsx (1)

4285-4361: 🛠️ Refactor suggestion

Improve test reliability and readability.

The current test implementation has several areas for improvement:

  1. Using setTimeout(0) is an anti-pattern and can lead to flaky tests
  2. Multiple act() wrappings make the test hard to read
  3. Missing intermediate assertions between filter changes

Consider this improved implementation:

 it('should handle filter changes in sequence', async () => {
   setItem('userId', '1');
   const mockChatsData = {
     chatsByUserId: [
       {
         _id: '1',
         isGroup: false,
         users: [{ _id: '1', firstName: 'John', lastName: 'Doe' }],
         messages: [],
         unseenMessagesByUsers: '{}',
       },
     ],
   };

   const mocks = [
     {
       request: {
         query: CHATS_LIST,
         variables: { id: '1' },
       },
       result: {
         data: mockChatsData,
       },
     },
   ];
   
   render(
     <MockedProvider mocks={mocks} addTypename={false}>
       <BrowserRouter>
         <Provider store={store}>
           <Chat />
         </Provider>
       </BrowserRouter>
     </MockedProvider>,
   );

   const allChatButton = await screen.findByTestId('allChat');
   const unreadChatButton = await screen.findByTestId('unreadChat');
   const groupChatButton = await screen.findByTestId('groupChat');

-  await act(async () => {
-    fireEvent.click(unreadChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(unreadChatButton);
+  await waitFor(() => {
+    expect(screen.getByTestId('unreadChat')).toHaveClass('active');
+  });

-  await act(async () => {
-    fireEvent.click(groupChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(groupChatButton);
+  await waitFor(() => {
+    expect(screen.getByTestId('groupChat')).toHaveClass('active');
+  });

-  await act(async () => {
-    fireEvent.click(allChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(allChatButton);
+  await waitFor(() => {
+    expect(screen.getByTestId('allChat')).toHaveClass('active');
+  });

   const contactCards = await screen.findAllByTestId('contactCardContainer');
   expect(contactCards).toHaveLength(mockChatsData.chatsByUserId.length);
 });

Likely invalid or redundant comment.

src/screens/UserPortal/Chat/Chat.spec.tsx Show resolved Hide resolved
@abbi4code
Copy link
Contributor Author

Regarding the removal of hideDrawer

The hideDrawer state and its resize logic can be removed since they don't affect the UI or component functionality. It's not used in rendering, CSS classes, or conditional display. Responsive behavior is already handled through CSS and flex properties, so this code is unnecessary

@abbi4code
Copy link
Contributor Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

✅ Actions performed

Full review triggered.

Copy link

codecov bot commented Jan 5, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 89.71%. Comparing base (0486d6d) to head (92dee41).
Report is 1 commits behind head on develop-postgres.

Additional details and impacted files
@@                  Coverage Diff                  @@
##           develop-postgres    #3163       +/-   ##
=====================================================
+ Coverage             19.97%   89.71%   +69.74%     
=====================================================
  Files                   302      323       +21     
  Lines                  7694     8452      +758     
  Branches               1678     1899      +221     
=====================================================
+ Hits                   1537     7583     +6046     
+ Misses                 6061      644     -5417     
- Partials                 96      225      +129     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share 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: 1

🧹 Nitpick comments (2)
src/screens/UserPortal/Chat/Chat.tsx (1)

305-305: Maps chat data to ContactCard as expected.
The usage of spread syntax for passing props is concise, but ensure each prop remains type-safe and tested. Since title logic depends on the user array’s indexing, consider adding a boundary check or fallback for robust error handling in future expansions.

src/screens/UserPortal/Chat/Chat.spec.tsx (1)

32-32: Consider using userEvent instead of fireEvent.

The commented import of userEvent suggests it was considered but not implemented. userEvent provides a more accurate simulation of user interactions compared to fireEvent. It better represents how users interact with your application by handling focus, blur, and other browser events more realistically.

-// import userEvent from '@testing-library/user-event';
+import userEvent from '@testing-library/user-event';
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0486d6d and 92dee41.

📒 Files selected for processing (2)
  • src/screens/UserPortal/Chat/Chat.spec.tsx (3 hunks)
  • src/screens/UserPortal/Chat/Chat.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Test Application
🔇 Additional comments (3)
src/screens/UserPortal/Chat/Chat.tsx (2)

140-140: Well-structured toggle function for the direct chat modal.
The straightforward arrow function that flips the state is clear and idiomatic React. Make sure to include or maintain corresponding tests validating the toggling behavior, ensuring full coverage of modal open/close actions.


150-150: Consistent pattern for toggling the group chat modal.
This approach matches the direct chat modal’s toggling pattern, enhancing consistency. Verify you have tests that confirm both creating a group chat flow and properly closing the modal, to preserve coverage gains.

src/screens/UserPortal/Chat/Chat.spec.tsx (1)

4285-4361: 🛠️ Refactor suggestion

Improve test reliability and assertions.

The current implementation has several anti-patterns that could make the tests flaky:

  1. Using setTimeout(0) is an anti-pattern and can lead to race conditions
  2. Multiple act() wrappings can be simplified
  3. Missing intermediate assertions between filter changes

Consider this improved implementation:

 it('should handle filter changes in sequence', async () => {
   setItem('userId', '1');
   const mockChatsData = {
     chatsByUserId: [
       {
         _id: '1',
         isGroup: false,
         users: [{ _id: '1', firstName: 'John', lastName: 'Doe' }],
         messages: [],
         unseenMessagesByUsers: '{}',
       },
     ],
   };

   const mocks = [
     {
       request: {
         query: CHATS_LIST,
         variables: { id: '1' },
       },
       result: {
         data: mockChatsData,
       },
     },
   ];
   
   render(
     <MockedProvider mocks={mocks} addTypename={false}>
       <BrowserRouter>
         <Provider store={store}>
           <Chat />
         </Provider>
       </BrowserRouter>
     </MockedProvider>,
   );

   const allChatButton = await screen.findByTestId('allChat');
   const unreadChatButton = await screen.findByTestId('unreadChat');
   const groupChatButton = await screen.findByTestId('groupChat');

-  await act(async () => {
-    fireEvent.click(unreadChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(unreadChatButton);
+  await waitFor(() => {
+    expect(unreadChatButton).toHaveClass('active');
+  });

-  await act(async () => {
-    fireEvent.click(groupChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(groupChatButton);
+  await waitFor(() => {
+    expect(groupChatButton).toHaveClass('active');
+  });

-  await act(async () => {
-    fireEvent.click(allChatButton);
-  });
-  await act(async () => {
-    await new Promise((resolve) => setTimeout(resolve, 0));
-  });
+  await userEvent.click(allChatButton);
+  await waitFor(() => {
+    expect(allChatButton).toHaveClass('active');
+  });

   const contactCards = await screen.findAllByTestId('contactCardContainer');
   expect(contactCards).toHaveLength(1);
 });

Likely invalid or redundant comment.

src/screens/UserPortal/Chat/Chat.spec.tsx Show resolved Hide resolved
@abbi4code
Copy link
Contributor Author

@coderabbitai full review

Copy link
Contributor

coderabbitai bot commented Jan 5, 2025

✅ Actions performed

Full review triggered.

@palisadoes palisadoes merged commit c8a1290 into PalisadoesFoundation:develop-postgres Jan 6, 2025
18 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.

2 participants