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/utils/useSession.test.tsx from Jest to Vitest #2952

Conversation

vivekbisen04
Copy link

@vivekbisen04 vivekbisen04 commented Dec 27, 2024

What kind of change does this PR introduce?

Refactoring from Jest to Vitest for the specified test file.

Issue Number

Fixes #2754

Did you add tests for your changes?

Yes, all test cases were updated and verified to work with Vitest.

Snapshots/Videos

Screenshot from 2024-12-27 08-52-38

If relevant, did you update the documentation?

Not applicable, as this is a refactor of existing tests.

Summary

  • Replaced Jest-specific functions and mocks with their Vitest equivalents.
  • Renamed the test file from .test.tsx to .spec.tsx.
  • Ensured all tests pass after migration using npm run test:vitest.

Does this PR introduce a breaking change?

No, it is a refactor of existing test cases with no changes to the codebase logic.

Other Information

  • Followed Vitest documentation and the base Vitest configuration from PR #2457.

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • Tests
    • Introduced comprehensive unit tests for the session management functionality.
    • Covered scenarios for visibility change handling, session timeout management, error handling, cleanup on unmount, handling missing data, and session data updates.
    • Removed the previous test suite for the useSession hook.

Copy link
Contributor

coderabbitai bot commented Dec 27, 2024

Walkthrough

This pull request involves the removal of the existing Jest test suite for the useSession hook in src/utils/useSession.test.tsx and the introduction of a new test suite in src/utils/useSession.spec.tsx using Vitest. The new suite includes comprehensive unit tests that cover various scenarios related to session management, such as visibility changes, session timeouts, error handling, and lifecycle management, ensuring robust functionality and error management.

Changes

File Change Summary
src/utils/useSession.spec.tsx Introduced a comprehensive suite of unit tests for the useSession hook using Vitest, covering visibility changes, timeout management, error handling, and cleanup.
src/utils/useSession.test.tsx Removed the existing Jest test suite for the useSession hook.

Assessment against linked issues

Objective Addressed Explanation
Replace Jest-specific functions with Vitest equivalents [#2754]
Rename test file to .spec.tsx [#2754]
Ensure tests pass with npm run test:vitest [#2754] Actual test run verification not visible in diff.
Maintain 100% test coverage [#2754] Coverage report not included in diff.

Possibly related issues

Suggested labels

refactor

Suggested reviewers

  • palisadoes

Poem

🐰 Hop, hop, testing we go!
From Jest to Vitest, watch our code flow
Sessions tracked with rabbit-like precision
No timeout escapes our keen vision
Testing magic, clean and bright! 🧪✨


📜 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 097b7a4 and 54f67b1.

📒 Files selected for processing (1)
  • src/utils/useSession.test.tsx (0 hunks)
💤 Files with no reviewable changes (1)
  • src/utils/useSession.test.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link
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/utils/useSession.spec.tsx (2)

478-509: Address Prettier warnings.

ESLint/Prettier flagged spacing, indentation, and missing trailing commas. Align the code with the project’s formatting rules to maintain consistency and avoid future merge conflicts.

Here’s an example partial fix for indentation/trailing commas around lines 505 and 539:

-      expect(toast.warning).toHaveBeenCalledWith('sessionWarning')
+      expect(toast.warning).toHaveBeenCalledWith('sessionWarning');

And:

-  expect(window.removeEventListener).toHaveBeenCalledWith(
-    'mousemove'
-    expect.any(Function)
-  );
+  expect(window.removeEventListener).toHaveBeenCalledWith(
+    'mousemove',
+    expect.any(Function),
+  );

Also applies to: 517-547, 578-589, 598-627

🧰 Tools
🪛 eslint

[error] 478-478: Delete ··

(prettier/prettier)


[error] 488-488: Delete ··

(prettier/prettier)


[error] 491-491: Delete ··

(prettier/prettier)


[error] 494-494: Delete ··

(prettier/prettier)


[error] 497-497: Delete ··

(prettier/prettier)


[error] 500-500: Delete ··

(prettier/prettier)


[error] 503-503: Delete ··

(prettier/prettier)


[error] 505-505: Insert ,

(prettier/prettier)


581-582: Unused parameters in arrow functions.

ESLint indicates that _ is assigned but never used. Consider renaming these unused parameters to _unused or omitting them altogether if not needed.

- const hasWarningTimeout = timeoutCalls.some((call: Parameters<typeof setTimeout>) => {
-   const [_, ms] = call;
+ const hasWarningTimeout = timeoutCalls.some((timeoutCall: Parameters<typeof setTimeout>) => {
+   const [, ms] = timeoutCall;

Also applies to: 587-588, 620-620

🧰 Tools
🪛 eslint

[error] 581-581: Insert ··

(prettier/prettier)


[error] 581-581: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


[error] 582-582: Replace ···· with ······

(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 ac36851 and 097b7a4.

📒 Files selected for processing (1)
  • src/utils/useSession.spec.tsx (1 hunks)
🧰 Additional context used
🪛 eslint
src/utils/useSession.spec.tsx

[error] 478-478: Delete ··

(prettier/prettier)


[error] 488-488: Delete ··

(prettier/prettier)


[error] 491-491: Delete ··

(prettier/prettier)


[error] 494-494: Delete ··

(prettier/prettier)


[error] 497-497: Delete ··

(prettier/prettier)


[error] 500-500: Delete ··

(prettier/prettier)


[error] 503-503: Delete ··

(prettier/prettier)


[error] 505-505: Insert ,

(prettier/prettier)


[error] 509-512: Delete ⏎⏎⏎

(prettier/prettier)


[error] 517-517: Delete ··

(prettier/prettier)


[error] 531-531: Insert ,

(prettier/prettier)


[error] 535-535: Insert ,

(prettier/prettier)


[error] 539-539: Insert ,

(prettier/prettier)


[error] 547-547: Delete ··

(prettier/prettier)


[error] 578-578: Delete ··

(prettier/prettier)


[error] 580-580: Insert ⏎····

(prettier/prettier)


[error] 581-581: Insert ··

(prettier/prettier)


[error] 581-581: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


[error] 582-582: Replace ···· with ······

(prettier/prettier)


[error] 583-583: Replace } with ··},⏎··

(prettier/prettier)


[error] 586-586: Insert ⏎····

(prettier/prettier)


[error] 587-587: Insert ··

(prettier/prettier)


[error] 587-587: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


[error] 588-588: Insert ··

(prettier/prettier)


[error] 589-589: Replace } with ··},⏎··

(prettier/prettier)


[error] 598-600: Delete ⏎⏎

(prettier/prettier)


[error] 601-601: Replace .spyOn(console,·'error') with ⏎····.spyOn(console,·'error')⏎····

(prettier/prettier)


[error] 603-603: Delete ··

(prettier/prettier)


[error] 605-605: Insert ⏎····

(prettier/prettier)


[error] 620-620: 'error' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 624-624: Delete ··

(prettier/prettier)


[error] 632-632: Delete ··

(prettier/prettier)


[error] 667-667: Replace call with (call)

(prettier/prettier)


[error] 669-669: Replace Math.abs(duration·-·expectedWarningTime)·<=·expectedWarningTime·*·0.05 with (⏎······Math.abs(duration·-·expectedWarningTime)·<=·expectedWarningTime·*·0.05⏎····)

(prettier/prettier)


[error] 672-672: Replace call with (call)

(prettier/prettier)


[error] 674-674: Replace Math.abs(duration·-·expectedSessionTime)·<=·expectedSessionTime·*·0.05 with (⏎······Math.abs(duration·-·expectedSessionTime)·<=·expectedSessionTime·*·0.05⏎····)

(prettier/prettier)

🔇 Additional comments (19)
src/utils/useSession.spec.tsx (19)

1-10: Well-structured test arrangement.

The new test file cleanly migrates from Jest to Vitest, demonstrating thorough coverage of session-related scenarios. Mocking react-toastify and react-i18next is concise and idiomatic, ensuring each test is isolated. Overall, these top lines do not raise immediate concerns.


13-23: Mocks align well with Vitest standards.

By mocking react-toastify and utils/errorHandler in this manner, each test runs in a self-contained environment. The approach is logically consistent and helps avoid side effects from external modules.


25-29: Appropriate i18n mocking.

Mocking react-i18next ensures the tests avoid real translation complexities and remain stable.


75-110: Effective usage of timers and event dispatch for session tests.

Fake timers are used correctly to advance time and validate warnings, and the test dispatches a visibility change event to simulate the user returning to the tab. This thoroughly validates session events.


112-147: Good coverage for visibility change edge cases.

The hidden state scenario ensures no premature warnings. This test verifies correct removal of event listeners, covering potential memory leaks or unexpected calls when the document is not visible.


149-184: Robust asserts for event listeners.

You verify that the listeners mousemove, keydown, and visibilitychange are attached correctly. This coverage ensures that any future changes to event listener logic must pass these tests.


187-209: Clear handling of session timeout logic.

Fake timers are advanced to simulate session expiration. The test includes checks for both localStorage clearance and toast calls. This ensures correct log-out behavior.


233-279: Thoughtful handling of token revocation failures.

Capturing console.error and verifying that it was called ensures robust error handling. This test effectively defends against silent failures in token revocation logic.


281-295: Use of global spies to verify session timeout is well-designed.

By spying on global.setTimeout, the suite ensures the correct scheduling of session events. This is a standard practice when testing time-based logic.


297-318: Correct usage of mocked error-handling for GraphQL queries.

Ensuring errorHandler is called during query failure guards against unhandled rejections or missing error checks.


320-356: Coverage of endSession logic.

Verifying that event listeners are removed confirms that resources are cleaned up and no memory leaks remain after the session ends.


358-401: Smart approach to tab visibility-based inactivity.

This test scenario simulates leaving and returning to the tab with partial inactivity across multiple intervals, ensuring that timeouts are recalculated appropriately.


403-450: Proper session timeout during hidden state inactivity.

Especially useful for real-life scenarios, the test confirms correct logout behavior even if a user remains away from the tab for extended periods of time.


452-474: Verification of logout flow and token revocation.

Ensuring that localStorage is cleared and a toast is displayed meets user expectations for sign-out flows. This coverage is important for security checks.


475-509: Extend session functionality validated.

The test confirms that extending the session resets warnings, ensuring a smooth user experience for those extending sessions.

🧰 Tools
🪛 eslint

[error] 478-478: Delete ··

(prettier/prettier)


[error] 488-488: Delete ··

(prettier/prettier)


[error] 491-491: Delete ··

(prettier/prettier)


[error] 494-494: Delete ··

(prettier/prettier)


[error] 497-497: Delete ··

(prettier/prettier)


[error] 500-500: Delete ··

(prettier/prettier)


[error] 503-503: Delete ··

(prettier/prettier)


[error] 505-505: Insert ,

(prettier/prettier)


513-543: Unmount listener cleanup.

Confirming removeEventListener was called on unmount helps avoid memory leaks. The approach is consistent with React’s lifecycle.

🧰 Tools
🪛 eslint

[error] 517-517: Delete ··

(prettier/prettier)


[error] 531-531: Insert ,

(prettier/prettier)


[error] 535-535: Insert ,

(prettier/prettier)


[error] 539-539: Insert ,

(prettier/prettier)


544-596: Graceful handling of missing community data.

Even when getCommunityData returns null, the tests confirm that session timeouts are still set properly with default values—a robust fallback scenario.

🧰 Tools
🪛 eslint

[error] 547-547: Delete ··

(prettier/prettier)


[error] 578-578: Delete ··

(prettier/prettier)


[error] 580-580: Insert ⏎····

(prettier/prettier)


[error] 581-581: Insert ··

(prettier/prettier)


[error] 581-581: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


[error] 582-582: Replace ···· with ······

(prettier/prettier)


[error] 583-583: Replace } with ··},⏎··

(prettier/prettier)


[error] 586-586: Insert ⏎····

(prettier/prettier)


[error] 587-587: Insert ··

(prettier/prettier)


[error] 587-587: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)


[error] 588-588: Insert ··

(prettier/prettier)


[error] 589-589: Replace } with ··},⏎··

(prettier/prettier)


600-627: Error handling on event listener registration.

The test forcibly throws an error and checks against console.error, ensuring the code logs unexpected issues properly. This scenario can reveal hidden device or environment constraints.

🧰 Tools
🪛 eslint

[error] 601-601: Replace .spyOn(console,·'error') with ⏎····.spyOn(console,·'error')⏎····

(prettier/prettier)


[error] 603-603: Delete ··

(prettier/prettier)


[error] 605-605: Insert ⏎····

(prettier/prettier)


[error] 620-620: 'error' is defined but never used.

(@typescript-eslint/no-unused-vars)


[error] 624-624: Delete ··

(prettier/prettier)


629-682: Timeout data updates are validated.

Your approach of fetching updated session timeouts and verifying their scheduling with setTimeout ensures timeouts match new data. The test is thorough, though appear aware of the tolerance check around ±5%.

🧰 Tools
🪛 eslint

[error] 632-632: Delete ··

(prettier/prettier)


[error] 667-667: Replace call with (call)

(prettier/prettier)


[error] 669-669: Replace Math.abs(duration·-·expectedWarningTime)·<=·expectedWarningTime·*·0.05 with (⏎······Math.abs(duration·-·expectedWarningTime)·<=·expectedWarningTime·*·0.05⏎····)

(prettier/prettier)


[error] 672-672: Replace call with (call)

(prettier/prettier)


[error] 674-674: Replace Math.abs(duration·-·expectedSessionTime)·<=·expectedSessionTime·*·0.05 with (⏎······Math.abs(duration·-·expectedSessionTime)·<=·expectedSessionTime·*·0.05⏎····)

(prettier/prettier)

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 27, 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.

You need to delete src/utils/useSession.test.tsx as requested in the issue

@palisadoes
Copy link
Contributor

Please fix the failing tests

@palisadoes palisadoes reopened this Dec 27, 2024
@palisadoes
Copy link
Contributor

Reopening. You don't have to close the PR. Just make the changes in your local branch and then push to your origin. The PR will automatically get updated and re-run all the workflows.

@vivekbisen04 vivekbisen04 deleted the useSession-jest-to-Vitest branch February 1, 2025 09:31
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