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

migration of People.test.tsx from jest to vitest #2609

Closed

Conversation

nadeemnagarji
Copy link

@nadeemnagarji nadeemnagarji commented Dec 5, 2024

What kind of change does this PR introduce?

Refactor
Issue Number:

Fixes #2576

Did you add tests for your changes?

Yes

Snapshots/Videos:
testcase passed

Summary

Migrating the tests of People.tsx Component from jest to vitest

Does this PR introduce a breaking change?
No

Other information

Have you read the contributing guide?

Yes

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new linting rules for enhanced TypeScript code quality.
    • Added new testing scripts for improved testing capabilities.
    • Implemented a new configuration for the Vitest testing framework.
  • Bug Fixes

    • Updated test configurations to use Vitest instead of Jest, ensuring better compatibility and performance.
  • Documentation

    • Updated configuration files to clarify linting and testing settings.
  • Chores

    • Cleaned up configuration files by removing unnecessary comments and adjusting timeout settings.
  • Refactor

    • Streamlined the ESLint configuration for better readability and maintainability.
    • Excluded specific directories from TypeScript compilation for improved performance.

Copy link

coderabbitai bot commented Dec 5, 2024

Walkthrough

The changes in this pull request involve significant updates to the project's configuration and testing framework. The ESLint configuration has been revised to enhance TypeScript linting rules, while the package.json file has been modified to include new dependencies and test scripts. The transition from Jest to Vitest for testing is reflected in the updates to various test files, including the replacement of Jest-specific functions with Vitest equivalents. Additionally, a new configuration file for Vitest has been introduced, and the TypeScript configuration has been adjusted to exclude certain directories.

Changes

File Change Summary
.eslintrc.json - Expanded rules with new TypeScript linting rules.
- Removed @typescript-eslint/ban-types rule.
- Updated naming-convention rule.
- Added ignorePatterns.
package.json - Updated multiple dependencies, including MUI and Apollo.
- Added new dependencies: @pdfme/schemas, chart.js, lcov-result-merger.
- Added test scripts for Vitest.
src/screens/UserPortal/People/People.test.tsx - Replaced Jest mocks with Vitest equivalents.
- Updated test function syntax from test to it.
src/setupTests.ts - Changed global fetch mock from Jest to Vitest.
- Updated timeout setting.
tsconfig.json - Added exclude property to ignore specific directories and files.
vitest.config.ts - Introduced Vitest configuration with plugins and coverage reporting settings.

Assessment against linked issues

Objective Addressed Explanation
Replace Jest-specific functions and mocks with Vitest equivalents (2576)
Ensure all tests in src/screens/UserPortal/People pass after migration (2576)
Maintain the test coverage for the file as 100% after migration (2576)

Possibly related issues

Possibly related PRs

Suggested labels

refactor, test

Suggested reviewers

  • palisadoes
  • varshith257
  • pranshugupta54

Poem

In code we hop, with changes bright,
From Jest to Vitest, we take flight.
Linting rules now sharp and clear,
Our tests will dance, have no fear!
With every line, our code will sing,
A better build, let’s see what it brings! 🐰✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1ece1b7 and 696726f.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json

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. (Experiment)
  • @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 Dec 5, 2024

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

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Congratulations on making your first PR! 🎊 If you haven't already, check out our Contributing Guidelines and PR Reporting Guidelines to ensure that you are following our guidelines for contributing and creating PR.

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

🧹 Outside diff range and nitpick comments (7)
vitest.config.ts (1)

19-34: Coverage configuration is comprehensive.

The coverage setup includes:

  • Istanbul provider
  • Multiple report formats
  • Appropriate exclusions
  • Dedicated reports directory

One suggestion: Consider adding minimum coverage thresholds to maintain code quality.

 coverage: {
   enabled: true,
   provider: 'istanbul',
   reportsDirectory: './coverage/vitest',
+  thresholds: {
+    lines: 80,
+    functions: 80,
+    branches: 80,
+    statements: 80
+  },
   exclude: [
src/setupTests.ts (1)

28-31: Consider replacing jest-preview with vitest-preview.

Since we're migrating from Jest to Vitest, consider using vitest-preview instead of commenting out jest-preview.

Would you like me to provide the configuration for vitest-preview?

.eslintrc.json (2)

79-85: Consider relaxing interface naming restrictions

The current configuration requires all interfaces to have either "Interface" or "TestInterface" prefix, which might be too restrictive and goes against common TypeScript conventions. Consider removing the prefix requirement to allow more natural interface naming.

{
  "selector": "interface",
-  "format": ["PascalCase"],
-  "prefix": ["Interface", "TestInterface"]
+  "format": ["PascalCase"]
}

Line range hint 1-15: Update ESLint configuration for Vitest

The configuration still includes Jest plugin in extends array while the project is migrating to Vitest. Consider adding Vitest ESLint plugin and removing Jest-specific configuration.

  "extends": [
    "plugin:react/recommended",
    "eslint:recommended",
-   "plugin:jest/recommended",
+   "plugin:vitest/recommended",
    "plugin:prettier/recommended",
    "plugin:@typescript-eslint/recommended",
    "eslint-config-prettier",
    "prettier"
  ],
package.json (1)

Line range hint 91-96: Remove Jest ESLint configuration

The ESLint configuration still includes Jest-specific settings. These should be removed as part of the migration to Vitest.

  "eslintConfig": {
    "extends": [
      "react-app",
-     "react-app/jest"
    ]
  },
src/screens/UserPortal/People/People.test.tsx (2)

Line range hint 98-106: Replace custom wait function with Vitest utilities

The custom wait function can be replaced with Vitest's built-in timer utilities for better test reliability.

-async function wait(ms = 100): Promise<void> {
-  await act(() => {
-    return new Promise((resolve) => {
-      setTimeout(resolve, ms);
-    });
-  });
-}
+import { vi } from 'vitest';
+const wait = async () => {
+  await vi.advanceTimersByTimeAsync(100);
+};

117-123: Add mock cleanup after tests

Consider adding mock cleanup to ensure tests don't affect each other.

vi.mock('react-router-dom', async () => {
  const actual = await vi.importActual('react-router-dom');
  return {
    ...actual,
    useParams: () => ({ orgId: '' }),
  };
});

+afterEach(() => {
+  vi.clearAllMocks();
+});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f9e10b8 and cca1300.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • .eslintrc.json (4 hunks)
  • package.json (3 hunks)
  • src/screens/UserPortal/People/People.test.tsx (5 hunks)
  • src/setupTests.ts (2 hunks)
  • tsconfig.json (1 hunks)
  • vitest.config.ts (1 hunks)
🔇 Additional comments (7)
vitest.config.ts (2)

15-18: LGTM! Test configuration is well structured.

The test configuration properly includes:

  • Correct test file patterns for both .spec and .test files
  • Global variables enabled for Vitest globals
  • JSDOM environment for DOM testing
  • Setup file correctly referenced

9-11: Verify if additional node polyfills are needed.

The configuration only includes the 'events' polyfill. Consider if other Node.js built-in modules are used in the tests that might need polyfilling.

✅ Verification successful

The 'events' polyfill is sufficient for test files

The codebase scan shows that among Node.js built-ins, only fs, path, and util are used, and these are primarily in setup scripts and test utilities, not in the actual test files that Vitest would run. The existing 'events' polyfill is adequate for the test environment as:

  • The fs usage in test files is only in checkEnvFile.test.ts which is testing file system operations
  • The util import in setupTests.ts is for test setup configuration
  • Other Node.js built-in usages are in scripts outside the test environment
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Node.js built-in module usage in test files
rg -t ts -t tsx "require\(['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" src/

Length of output: 135


Script:

#!/bin/bash
# Search for Node.js built-in module usage in test files using both import and require patterns
rg -t typescript -t javascript "(?:import|require)\(['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "**/*.test.{ts,js}" "**/*.spec.{ts,js}"

# Also check for ES module style imports
rg -t typescript -t javascript "^import .* from ['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "**/*.test.{ts,js}" "**/*.spec.{ts,js}"

# Check if any test files use other Node.js built-ins
rg -t typescript -t javascript "(?:import|require)\(['\"](?:child_process|cluster|dgram|dns|net|os|process|querystring|readline|repl|tls|tty|v8|vm|zlib)['\"]" "**/*.test.{ts,js}" "**/*.spec.{ts,js}"

# Check for ES module style imports of other Node.js built-ins
rg -t typescript -t javascript "^import .* from ['\"](?:child_process|cluster|dgram|dns|net|os|process|querystring|readline|repl|tls|tty|v8|vm|zlib)['\"]" "**/*.test.{ts,js}" "**/*.spec.{ts,js}"

Length of output: 879


Script:

#!/bin/bash
# Search for Node.js built-in module usage in test files without file type specification
rg "(?:import|require)\(['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "src/**/*.test.ts" "src/**/*.spec.ts"

# Also check for ES module style imports
rg "^import .* from ['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "src/**/*.test.ts" "src/**/*.spec.ts"

# Let's also check the source files that might be imported by tests
rg "(?:import|require)\(['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "src/**/*.ts"

# And ES module style imports in source files
rg "^import .* from ['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]" "src/**/*.ts"

Length of output: 831


Script:

#!/bin/bash
# First, let's find where the test files are located
fd -e ts -e js ".*\.(test|spec)\.(ts|js)$"

# Find all TypeScript/JavaScript files to check Node.js built-in usage
fd -e ts -e js | xargs rg "(?:import|require)\(['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]"

# Check for ES module style imports in all TypeScript/JavaScript files
fd -e ts -e js | xargs rg "^import .* from ['\"](?:assert|buffer|crypto|fs|http|https|path|stream|url|util)['\"]"

Length of output: 1482

tsconfig.json (1)

21-22: LGTM! TypeScript configuration aligns with Vitest setup.

The exclude patterns are appropriate and match the coverage exclusions in vitest.config.ts.

src/setupTests.ts (1)

6-7: LGTM! Correct migration of fetch mock to Vitest.

The global fetch mock has been properly migrated from Jest to Vitest.

package.json (1)

71-73: LGTM! New Vitest scripts added correctly

The new Vitest scripts are well-structured and follow common conventions.

src/screens/UserPortal/People/People.test.tsx (2)

127-137: LGTM! Properly migrated matchMedia mock

The matchMedia mock has been correctly updated to use Vitest's mocking utilities.


Line range hint 140-157: LGTM! Test cases successfully migrated to Vitest

The test cases have been properly migrated from Jest to Vitest while maintaining the same functionality and assertions.

Also applies to: 158-179, 180-205, 206-231

src/setupTests.ts Outdated Show resolved Hide resolved
package.json Show resolved Hide resolved
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 and nitpick comments (3)
src/setupTests.ts (2)

29-32: Remove commented-out Jest Preview configuration

Since we're migrating to Vitest, we should either:

  1. Remove the commented Jest Preview configuration
  2. Replace it with the Vitest equivalent if preview functionality is needed

34-37: Update timeout configuration comment

The comment "Use the global setTimeout function" is outdated and doesn't match the actual implementation using Vitest's configuration.

-// Use the global setTimeout function
+// Configure global test timeout
beforeAll(() => {
  vi.setConfig({ testTimeout: 15000 });
});
package.json (1)

Line range hint 89-92: Remove Jest-specific ESLint configuration

Since we're migrating to Vitest, the Jest-specific ESLint configuration should be updated.

  "eslintConfig": {
    "extends": [
-     "react-app",
-     "react-app/jest"
+     "react-app"
    ]
  },
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between cca1300 and 1ece1b7.

📒 Files selected for processing (2)
  • package.json (3 hunks)
  • src/setupTests.ts (2 hunks)
🔇 Additional comments (4)
src/setupTests.ts (1)

6-8: LGTM: Proper Vitest setup and mocking

The migration from Jest to Vitest is correctly implemented for the imports and global fetch mock.

package.json (3)

71-73: LGTM: Vitest test scripts properly configured

The test scripts for Vitest are correctly set up with appropriate commands for running tests, watch mode, and coverage.


127-130: LGTM: Essential Vitest dependencies added

The necessary Vitest-related dependencies have been added with appropriate versions:

  • @typescript-eslint updates for better TypeScript support
  • @vitest/coverage-istanbul for coverage reporting
  • @vitest/ui for the Vitest UI interface

Line range hint 141-144: Consider removing Jest dependencies

Since we're migrating to Vitest, consider removing Jest-related dependencies:

  • jest
  • jest-localstorage-mock
  • jest-location-mock
  • jest-preview

However, verify that all test files have been migrated before removing these dependencies.

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

Please fix the conflicting files

@nadeemnagarji
Copy link
Author

I have made changes in vitest.config.ts to make sure that the tests run. When I revert to the original vitest.config.ts of the develop branch the tests don't run as expected and I get the error saying "No test files found, exiting with code 1"

@palisadoes
Copy link
Contributor

  1. Please make your changes against the develop-postgres branch.
  2. Update your local branch with the latest upstream of the develop-postgres branch
  3. Make sure your local branch is not named develop-postgres

Closing

@palisadoes palisadoes closed this Dec 12, 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