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: Simplified and improved the Jest test #3846

Open
wants to merge 3 commits into
base: canary
Choose a base branch
from

Conversation

Ultimecia1463
Copy link

@Ultimecia1463 Ultimecia1463 commented Oct 5, 2024

📝 Description

Simplified and improved the Jest test setup by enhancing global mocks for matchMedia and ResizeObserver, and optimized handling of environment variables for React's strict mode configuration.

⛳️ Current behavior (updates)

  • Jest test environment had redundant or outdated mock implementations.
  • Environment variable handling for React's strict mode was basic and could result in inconsistencies across environments.

🚀 New behavior

  • Replaced redundant getComputedStyle reassignment.
  • Mocked window.matchMedia and global.ResizeObserver using jest.fn with enhanced structure.
  • Improved boolean parsing of STRICT_MODE using JSON.parse for better flexibility and correctness.
  • Made the test setup more maintainable and efficient without changing core logic.

💣 Is this a breaking change (Yes/No):

No

Summary by CodeRabbit

  • New Features

    • Enhanced package dependency checking and upgrading process.
    • Improved asynchronous file operations for package processing.
    • Updated testing environment configuration for better reliability.
  • Bug Fixes

    • Corrected regex filter for package names to ensure proper matching.
  • Chores

    • Streamlined setup process for the testing environment.

Copy link

changeset-bot bot commented Oct 5, 2024

⚠️ No Changeset found

Latest commit: 5ce9b39

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

Copy link

vercel bot commented Oct 5, 2024

@Ultimecia1463 is attempting to deploy a commit to the NextUI Inc Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 5, 2024

Walkthrough

The changes involve updates to three script files: check-rap-updates.ts, fix-rap.ts, and setup-test.ts. The modifications enhance package dependency checking and upgrading logic, transition file operations from synchronous to asynchronous methods, and refine the testing environment setup. Key improvements include the introduction of concurrent processing for package files and better error handling, along with adjustments to configuration for testing.

Changes

File Change Summary
scripts/check-rap-updates.ts Added checks for --upgrade flag, refactored checkForUpdates for concurrent processing using Promise.all, corrected regex for package names, and improved logging statements.
scripts/fix-rap.ts Transitioned to asynchronous file operations, updated function signatures to async, replaced synchronous loops with Promise.all, and improved error handling.
scripts/setup-test.ts Simplified setup by removing direct assignment of window.getComputedStyle, refined conditional assignment of window.matchMedia, and updated reactStrictMode configuration.

Suggested labels

👀 Status: In Review


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 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
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 and nitpick comments (4)
scripts/setup-test.ts (2)

4-8: Improved mock implementation for window.matchMedia

The changes to the window.matchMedia mock implementation are good. The conditional check prevents unnecessary overwriting, and the configurable: true setting allows for flexibility in testing.

Consider adding a comment explaining why enumerable was removed from the property descriptor, as it might not be immediately clear to other developers.


31-33: Improved reactStrictMode configuration

The update to the reactStrictMode configuration is a significant improvement. Using JSON.parse ensures correct boolean parsing of the STRICT_MODE environment variable, with a default value of false if not set.

For added clarity, consider adding a comment explaining the expected values for the STRICT_MODE environment variable:

// STRICT_MODE environment variable should be 'true' or 'false'
reactStrictMode: JSON.parse(process.env.STRICT_MODE || "false"),
scripts/check-rap-updates.ts (2)

13-19: Great improvements to concurrency and filtering

The changes here are excellent:

  1. Concurrent processing of package.json files will improve performance.
  2. The regex filter correction ensures proper package name matching.
  3. Using the shouldUpgrade flag for the upgrade option is consistent.

Consider adding a comment explaining the regex pattern for better maintainability:

filter: /^@react-(aria|stately|types)\/.*/, // Matches @react-aria/*, @react-stately/*, and @react-types/* packages

40-46: Excellent main function improvements

The enhancements to the main function are commendable:

  1. Concurrent processing of directories for better performance.
  2. Added error handling to improve script robustness.
  3. Clear completion message for better user feedback.

These changes significantly improve the script's efficiency and error handling.

Consider adding more detailed error logging:

console.error('Error during package checks:', error.message, '\nStack:', error.stack);

This would provide more context for debugging in case of errors.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 780ba43 and 5ce9b39.

📒 Files selected for processing (3)
  • scripts/check-rap-updates.ts (1 hunks)
  • scripts/fix-rap.ts (1 hunks)
  • scripts/setup-test.ts (3 hunks)
🔇 Additional comments (13)
scripts/setup-test.ts (2)

22-22: Improved code readability

The addition of an empty line enhances the code's readability by clearly separating different sections of the setup.


Line range hint 1-33: Overall improvements to test setup

The changes in this file successfully achieve the PR objectives of simplifying and enhancing the Jest test setup. Key improvements include:

  1. More robust window.matchMedia mocking
  2. Better code organization
  3. Improved handling of the reactStrictMode configuration

These changes contribute to a more maintainable and efficient test environment. Great work!

scripts/check-rap-updates.ts (4)

5-7: LGTM: Upgrade flag check added

The addition of the shouldUpgrade constant is a good practice. It allows for more flexible control over the script's behavior through command-line arguments.


23-30: Improved logging and output clarity

The enhancements to the logging are valuable:

  1. Clearer output for upgrades found.
  2. New condition to log when no updates are found, improving completeness.
  3. Conditional logging for upgrades, consistent with the shouldUpgrade flag.

These changes will make it easier to understand the script's actions and results.


33-33: Enhanced error logging

The improved error logging, which now includes the file path, is an excellent addition. This will significantly aid in debugging by providing more context when errors occur.


35-35: Correct Promise.all closure

The closing bracket for the Promise.all call is correctly placed, matching the opening on line 14.

scripts/fix-rap.ts (7)

3-3: Good Practice: Using 'fs' Promises API for Asynchronous File Operations

The import statement correctly uses the promises API from the 'fs' module, facilitating asynchronous file operations without blocking the event loop.


9-9: Regex Update: Now Includes '@react-types' Dependencies

The regular expression has been updated to include '@react-types', ensuring that dependencies matching '@react-aria', '@react-stately', and '@react-types' are processed appropriately.


17-17: Updated 'processPackageFiles' Function to be Asynchronous

The processPackageFiles function is now declared as async, allowing for non-blocking I/O operations and improved performance.


22-36: Refactored File Processing to Use Asynchronous Operations and Concurrency

The code within processPackageFiles has been refactored to use Promise.all and async/await, processing the package files concurrently. This change enhances performance by allowing multiple file operations to occur simultaneously.


25-26: Proper Use of Asynchronous File Reading and JSON Parsing

The code correctly uses await fs.readFile to read file contents asynchronously and then parses the JSON data, ensuring efficient, non-blocking operation.


30-31: Proper Use of Asynchronous File Writing

The code correctly uses await fs.writeFile to write the updated package data asynchronously and provides feedback upon successful operation.


42-46: Asynchronous 'main' Function with Concurrent Directory Processing

The main function has been updated to be asynchronous and now processes directories concurrently using Promise.all. This improves the script's performance when dealing with multiple directories.

Comment on lines 18 to 20
const filePaths = glob.sync(resolve(path, '**/package.json'), {
ignore: '**/node_modules/**',
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Suggestion: Use Asynchronous 'glob' Function for Consistency

While processPackageFiles is now asynchronous, it still uses the synchronous glob.sync method. Consider using the asynchronous glob function to avoid blocking the event loop and ensure full asynchronicity in your file operations.

You can modify the code as follows:

- const filePaths = glob.sync(resolve(path, '**/package.json'), {
-   ignore: '**/node_modules/**',
- });
+ const filePaths = await glob(resolve(path, '**/package.json'), {
+   ignore: '**/node_modules/**',
+ });

If glob does not natively support promises, you can use util.promisify to convert it:

import { promisify } from 'util';
const globAsync = promisify(glob);

Then update the code:

const filePaths = await globAsync(resolve(path, '**/package.json'), {
  ignore: '**/node_modules/**',
});

This change ensures that all file system operations within processPackageFiles are fully asynchronous.

@Ultimecia1463 Ultimecia1463 changed the title Ultimecia1463 patch 1 refactor: Simplified and improved the Jest test Oct 6, 2024
@Ultimecia1463
Copy link
Author

@jrgarciadev

@wingkwong wingkwong self-assigned this Oct 11, 2024
@wingkwong wingkwong added this to the v2.5.0 milestone Oct 11, 2024
Copy link
Member

@wingkwong wingkwong left a comment

Choose a reason for hiding this comment

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

Mocked window.matchMedia and global.ResizeObserver using jest.fn with enhanced structure.

Made the test setup more maintainable and efficient without changing core logic.

which part of code refers to these statements?


if(shouldUpgrade && upgraded) {
console.log(`✅ Upgraded packages in ${filePath}`);
if (Object.keys(upgraded).length > 0) {
Copy link
Member

Choose a reason for hiding this comment

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

No overload matches this call.
  Overload 1 of 2, '(o: {}): string[]', gave the following error.
    Argument of type 'void | PackageFile | Index<string>' is not assignable to parameter of type '{}'.
      Type 'void' is not assignable to type '{}'.
  Overload 2 of 2, '(o: object): string[]', gave the following error.
    Argument of type 'void | PackageFile | Index<string>' is not assignable to parameter of type 'object'.
      Type 'void' is not assignable to type 'object'.ts(2769)

@@ -22,7 +19,7 @@ if (typeof window.matchMedia !== "function") {
});
}

// Workaround https://github.com/jsdom/jsdom/issues/2524#issuecomment-897707183
Copy link
Member

Choose a reason for hiding this comment

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

why is this line removed? it's not resolved.

configure({
reactStrictMode: process.env.STRICT_MODE === "true",
reactStrictMode: JSON.parse(process.env.STRICT_MODE || "false"),
Copy link
Member

Choose a reason for hiding this comment

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

in which case this change would benefit?

@wingkwong wingkwong assigned Ultimecia1463 and unassigned wingkwong Oct 11, 2024
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