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

feat!: Migrate Testing Framework from Jest to Vitest #2457

Conversation

prayanshchh
Copy link

@prayanshchh prayanshchh commented Nov 20, 2024

What kind of change does this PR introduce?
configuring vitest for testing, adds a test file to check if this configuration is working as expected

Issue Number:
#2456

Fixes #

Did you add tests for your changes?
No

Snapshots/Videos:

Screencast.from.2024-11-20.19-38-55.webm

This is test was using Jest, it was updated to use vitest to show vitest configuration is working as expected

Screencast.from.2024-11-20.19-42-04.webm

If relevant, did you update the documentation?
No

Summary

Does this PR introduce a breaking change?
Yes

Note
This PR introduces a breaking change, and as a result, the overall test coverage may temporarily fall below 95% during the migration process.

Action Items:

  1. Ensure that test coverage for the specific files being worked on is at 100% locally.
  2. Contributors should verify the file's test coverage from CI and include a screenshot/video of 100% coverage for their respective files as part of the PR review process.

This will help maintain the integrity of our test suite while we transition.

Have you read the contributing guide?
Yes

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new dependencies and updated existing ones to enhance testing capabilities.
    • Added new scripts for running tests using Vitest.
  • Bug Fixes

    • Improved test execution workflow with specific commands and conditions.
  • Documentation

    • Enhanced test file documentation for clarity.
  • Chores

    • Updated configuration files to streamline testing processes and exclude unnecessary files from linting and compilation.
    • Added exclusions in TypeScript configuration to optimize compilation.
    • Updated GitHub Actions workflow for better test execution and branch validation.
    • Refined Jest configuration for more precise test file matching.
    • Updated ESLint ignore settings to exclude additional files.

Copy link

coderabbitai bot commented Nov 20, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The pull request introduces several updates to the talawa-admin project, primarily focusing on dependency management and testing framework enhancements. Key changes include the addition of new dependencies, updates to existing ones, and the introduction of new testing scripts in package.json. The vitest.config.ts file is configured for the Vitest testing framework, while the .eslintignore file is updated to exclude specific files from linting. Additionally, modifications to GitHub Actions workflows improve test execution and enforce branch validation.

Changes

File Change Summary
package.json - Added dependency: vite-plugin-node-polyfills (^0.22.0)
- Updated: vite-tsconfig-paths (^5.1.3)
- Added devDependency: @vitest/coverage-istanbul (^2.1.5)
- Updated: @testing-library/jest-dom (^6.6.3)
- Added scripts: test:vitest, test:vitest:watch, test:vitest:coverage.
vitest.config.ts - Configured Vitest with plugins for React, node polyfills, and TypeScript paths
- Defined test patterns and coverage reporting settings.
.eslintignore - Added exclusions for package.json, package-lock.json, and tsconfig.json.
src/components/AddOn/AddOn.spec.tsx - Enhanced tests with documentation comments, updated imports, and added mocking for store and translation utilities.
.github/workflows/pull-request.yml - Renamed step to "Run Jest Tests"
- Added step for "Run Vitest Tests"
- Introduced job Check-Target-Branch.
jest.config.js - Updated testMatch to match only .test files
- Adjusted setupFiles to include whatwg-fetch.
tsconfig.json - Added exclude property to omit node_modules, dist, and vitest.config.ts from compilation.

Possibly related issues

Possibly related PRs

Suggested reviewers

  • palisadoes
  • varshith257
  • AVtheking
  • gautam-divyanshu
  • Doraemon012

🐰 In the land of code, where rabbits hop,
Dependencies updated, we’ll never stop!
With Vitest in hand, our tests will run bright,
Hopping through scripts, everything feels right!
So let’s cheer for changes, both big and small,
In the world of Talawa, we’ll conquer them all! 🌟


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

github-actions bot commented Nov 20, 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

@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)
vitest.config.ts (1)

13-16: Consider additional test file patterns

The current patterns might miss some common test file locations. Consider adding:

  • src/**/*.{test,spec}.{cjs,mjs} for CommonJS/ESM tests
  • tests/**/*.{js,jsx,ts,tsx} for tests outside src
 include: [
   'src/**/__tests__/**/*.{js,jsx,ts,tsx}',
   'src/**/*.{spec,test}.{js,jsx,ts,tsx}',
+  'src/**/*.{test,spec}.{cjs,mjs}',
+  'tests/**/*.{js,jsx,ts,tsx}'
 ],
package.json (3)

Line range hint 76-77: Test script configuration needs update

The test scripts still reference Jest configurations while the PR aims to migrate to Vitest. This could cause confusion during the transition period.

Consider:

  1. Gradually migrating tests to Vitest
  2. Running both test suites during transition
  3. Creating a documentation note about the migration status

Also applies to: 83-84


Line range hint 164-167: Review version constraints in resolutions

The resolutions section specifies older versions of React types (17.0.2) while the project uses React 18. This might cause type mismatches.

Update the resolutions to match the project's React version:

  "resolutions": {
    "@apollo/client": "^3.4.0-beta.19",
-   "@types/react": "17.0.2",
-   "@types/react-dom": "17.0.2",
+   "@types/react": "^18.3.12",
+   "@types/react-dom": "^18.3.1",
    "graphql": "^16.5.0"
  },

Node.js version requirements are inconsistent across the project

The CI workflows are configured to use Node.js 22.x, while package.json specifies ">=20.x". This inconsistency could lead to confusion:

  • CI workflows in .github/workflows/ enforce Node.js 22.x
  • package.json allows Node.js versions >=20.x
  • This mismatch should be aligned to ensure consistent behavior across development and CI environments
🔗 Analysis chain

Line range hint 169-171: Verify Node.js version compatibility

The Node.js version requirement (>=20.x) is quite high and might affect CI/CD environments or contributors with older Node versions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if CI configs specify Node version
rg -l "node-version|nodejs-version" .github/workflows/

Length of output: 118


Script:

#!/bin/bash
# Check Node.js version specifications in CI workflows
rg "node-version" .github/workflows/

Length of output: 429


Script:

#!/bin/bash
# Check package.json for Node.js version requirements
cat package.json | jq '.engines'

Length of output: 55

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 86849df and cb477a5.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • package.json (3 hunks)
  • src/vitestconfig.test.ts (1 hunks)
  • vitest.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/vitestconfig.test.ts
🔇 Additional comments (4)
vitest.config.ts (3)

19-23: 🛠️ Refactor suggestion

Add coverage thresholds

While coverage reporting is configured, setting minimum coverage thresholds helps maintain code quality standards during the migration from Jest.

 coverage: {
   enabled: true,
   provider: 'istanbul',
   reporter: ['text', 'html', 'text-summary'],
+  thresholds: {
+    statements: 80,
+    branches: 80,
+    functions: 80,
+    lines: 80
+  }
 },

Let's check the current coverage thresholds in Jest configuration to maintain consistency:

✅ Verification successful

Let me check the actual thresholds from the Jest configuration file.


Update coverage thresholds to match or improve upon Jest configuration

The Jest configuration has lower coverage thresholds (20% for lines and statements) compared to the suggested 80%. Since this is a migration from Jest to Vitest, we should at least maintain the existing thresholds and potentially improve them gradually.

 coverage: {
   enabled: true,
   provider: 'istanbul',
   reporter: ['text', 'html', 'text-summary'],
+  thresholds: {
+    statements: 20,
+    lines: 20
+  }
 },

Consider gradually increasing these thresholds as test coverage improves during the migration process.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Jest coverage configuration
echo "Searching for existing Jest coverage thresholds..."
rg -t json -t js "coverageThreshold" .

Length of output: 189


Script:

#!/bin/bash
# Get the content of jest.config.js to see the coverage thresholds
cat jest.config.js

Length of output: 2174


1-11: Verify if additional polyfills are needed for Jest compatibility

The current configuration only includes the 'events' polyfill. During migration from Jest, additional Node.js built-ins might be needed (e.g., 'buffer', 'process', 'util') as Jest automatically provides these in its test environment.

Let's scan the codebase for potential Node.js built-in usage in tests:

✅ Verification successful

No additional Node.js polyfills needed beyond 'events'

The codebase scan shows that while there is significant usage of event-related functionality (EventEmitter patterns, emit/on), there are no direct imports or usage of other Node.js built-in modules like 'buffer', 'process', 'util', etc. in the test files. The only Node.js module imports found are 'fs' in setup files which are not part of the test suite execution. The current polyfill configuration including only 'events' is sufficient.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for common Node.js built-in modules in test files
echo "Searching for Node.js built-in usage in tests..."
rg -t ts -t tsx -t js -t jsx \
  -e "require\(['\"](?:buffer|process|util|stream|path)" \
  -e "from ['\"](?:buffer|process|util|stream|path)" \
  'src/**/*.{test,spec}.*'

Length of output: 300


Script:

#!/bin/bash
# Let's try a different approach to search for Node.js built-in usage
# First, let's find all test files
echo "Finding test files..."
fd -e test.ts -e test.tsx -e test.js -e test.jsx -e spec.ts -e spec.tsx -e spec.js -e spec.jsx

echo -e "\nSearching for Node.js built-in usage in these files..."
# Use ripgrep without file type restrictions
rg "(?:require|from) ['\"](?:buffer|process|util|stream|path|crypto|fs|os)" \
   -g '*.test.*' -g '*.spec.*'

echo -e "\nChecking for event emitter usage in tests..."
rg "(?:EventEmitter|emit\(|on\()" \
   -g '*.test.*' -g '*.spec.*'

Length of output: 51120


5-25: Verify Jest compatibility settings

As this is a migration from Jest, ensure these critical compatibility aspects are addressed:

  1. Test environment globals (Jest auto-includes certain globals)
  2. Timer mocks behavior
  3. Snapshot testing compatibility

Let's scan for Jest-specific features that might need migration:

✅ Verification successful

Based on the search results, I can see extensive usage of Jest-specific features in the test files, including:

  1. Timer mocks (jest.useFakeTimers(), jest.useRealTimers())
  2. Spy functionality (jest.spyOn())
  3. Mock implementations (jest.mock(), jest.fn())

The current Vitest configuration already includes:

  • jsdom environment
  • coverage reporting
  • globals enabled

However, let's verify if Vitest has built-in compatibility with these Jest APIs:


Based on the findings, I can now provide a definitive response about the Vitest configuration and Jest compatibility:

Vitest configuration is compatible with Jest APIs

The current configuration already includes the essential compatibility settings:

  1. globals: true - Enables Jest-compatible global APIs
  2. environment: 'jsdom' - Provides Jest-like DOM environment
  3. Package.json shows both Vitest and Jest-compatible testing libraries are installed

No additional configuration is needed as:

  • Vitest has built-in Jest API compatibility including timer mocks, spies, and mock implementations
  • The test files can continue using Jest-style APIs like jest.spyOn(), jest.mock(), etc.
  • Coverage reporting is properly configured with Istanbul provider
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for Jest-specific features that might need migration
echo "Checking Jest-specific feature usage..."
rg -t ts -t tsx -t js -t jsx \
  -e "jest\.(useFakeTimers|spyOn|mock|unmock)" \
  -e "beforeEach\(jest" \
  -e "toMatchSnapshot" \
  'src/**/*.{test,spec}.*'

Length of output: 258


Script:

#!/bin/bash
# Let's try a different approach to search for Jest-specific features
echo "Checking for Jest-specific features in test files..."
rg --type-add 'test:*.{test,spec}.{js,jsx,ts,tsx}' --type test \
  -e "jest\." \
  -e "toMatchSnapshot" \
  -e "useFakeTimers" \
  -e "spyOn" \
  -A 2

# Also check for test files to understand the test patterns
echo -e "\nListing test files:"
fd -e test.ts -e test.tsx -e test.js -e test.jsx -e spec.ts -e spec.tsx -e spec.js -e spec.jsx

Length of output: 183081


Script:

#!/bin/bash
# Check if vitest package.json or docs are present to verify compatibility
fd -e json -e md "vitest|jest" . | xargs cat

Length of output: 46


Script:

#!/bin/bash
# Let's check package.json for vitest dependencies and configuration
cat package.json

# Also check if there are any vitest setup files
fd -e ts -e js "vitest.setup|vitest.config"

Length of output: 5770


Script:

#!/bin/bash
# Let's check the vitest config file to understand the setup
cat vitest.config.ts

# Also check if there are any test setup files that might handle Jest compatibility
fd -e ts -e js "setup" test

Length of output: 699

package.json (1)

69-69: Verify polyfill plugin compatibility with testing setup

The addition of vite-plugin-node-polyfills is good for handling Node.js built-ins, but ensure it's properly configured in your Vitest setup.

✅ Verification successful

vite-plugin-node-polyfills is properly configured and used

The plugin is correctly set up in vitest.config.ts with specific polyfill inclusion for the 'events' module, which is appropriate for the testing environment. The configuration aligns well with both Vitest and the project's testing needs.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if vite config exists and uses the polyfills plugin
rg -l "vite-plugin-node-polyfills" --type ts

Length of output: 61


Script:

#!/bin/bash
# Check how the polyfills plugin is configured in vitest.config.ts
cat vitest.config.ts

Length of output: 579

package.json Show resolved Hide resolved
@varshith257
Copy link
Member

varshith257 commented Nov 20, 2024

src/components/AddOn/AddOn.test.tsx

Try migrating these tests into vitest and rename these vitest files as AddOn.spec.tsx

@varshith257
Copy link
Member

In vitest config similar to jest patter match with *vitest.test.tsx

@varshith257 varshith257 added test Testing application ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files labels Nov 20, 2024
@varshith257 varshith257 self-assigned this Nov 20, 2024
@varshith257
Copy link
Member

https://github.com/PalisadoesFoundation/talawa-admin/actions/runs/11940694150/job/33283928389?pr=2459#step:10:10

Add package.json and package.lock.json to ignore lint files so that workflow passes

vitest.config.ts Outdated Show resolved Hide resolved
@prayanshchh
Copy link
Author

prayanshchh commented Nov 21, 2024

src/components/AddOn/AddOn.test.tsx

Try migrating these tests into vitest and rename these vitest files as AddOn.spec.tsx

to do this I will need to extend Vitest's expect with the custom matchers from jest-dom (as it uses toBeInTheDocument) , I will need to install
testing-library/jest-dom

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 and nitpick comments (4)
vitest.config.ts (1)

7-13: Consider including additional Node.js polyfills.

While 'events' is included, you might need other common Node.js built-ins that Jest automatically provides. Common modules include 'buffer', 'process', and 'util'.

 nodePolyfills({
-  include: ['events'],
+  include: ['events', 'buffer', 'process', 'util'],
 }),
src/components/AddOn/AddOn.spec.tsx (3)

7-8: Consider organizing imports by category.

Group related imports together for better maintainability:

  1. React and testing libraries
  2. Router and state management
  3. Component and utilities
import React from 'react';
import { render } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { describe, test, expect, vi } from 'vitest';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { MockedProvider } from '@apollo/react-testing';
import { I18nextProvider } from 'react-i18next';
-import '@testing-library/jest-dom';
-import { describe, test, expect, vi } from 'vitest';

17-24: Enhance store mock configuration.

The current store mock only provides basic function stubs. Consider adding:

  1. Initial state configuration
  2. Return values for getState
  3. Implementation for dispatch to track dispatched actions
vi.mock('state/store', () => ({
  store: {
-    // Mock store configuration if needed
+    // Provide initial state matching the actual store structure
+    getState: vi.fn(() => ({
+      // Add your initial state here
+      // Example: user: { isLoggedIn: false }
+    })),
    subscribe: vi.fn(),
-    dispatch: vi.fn(),
+    dispatch: vi.fn((action) => {
+      // Track dispatched actions if needed for assertions
+      return action;
+    }),
  },
}));

Line range hint 33-65: Consider adding more comprehensive test coverage.

While the current tests cover basic rendering, consider adding:

  1. Error handling scenarios
  2. User interaction tests (clicks, inputs)
  3. Loading states
  4. Edge cases with different prop combinations

Example additional test:

test('should handle user interactions', async () => {
  const { getByTestId } = render(
    <MockedProvider addTypename={false} link={link}>
      <BrowserRouter>
        <Provider store={store}>
          <I18nextProvider i18n={i18nForTest}>
            <AddOn />
          </I18nextProvider>
        </Provider>
      </BrowserRouter>
    </MockedProvider>
  );
  
  // Add interaction tests here
  // Example: await userEvent.click(getByTestId('some-button'));
  // Example: expect(someMockFunction).toHaveBeenCalled();
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 17baee2 and 0fc12b2.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • .eslintignore (1 hunks)
  • package.json (4 hunks)
  • src/components/AddOn/AddOn.spec.tsx (1 hunks)
  • src/vitest.test.tsx (1 hunks)
  • vitest.config.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .eslintignore
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json
🔇 Additional comments (6)
src/vitest.test.tsx (2)

1-1: LGTM! Correct imports for Vitest.

The import statement correctly includes the essential Vitest testing utilities.


1-8: ⚠️ Potential issue

Missing tests mentioned in PR objectives.

The PR objectives mention tests for the askForCustomPort function that should demonstrate:

  1. Return of default port when no input is provided
  2. Return of user-provided port
  3. Mocking of the inquirer module

These tests are essential for validating the Vitest configuration with real use cases from your codebase.

Let's verify if these tests exist elsewhere:

Would you like me to help you implement these tests in this file or create a separate test file?

vitest.config.ts (3)

1-4: LGTM! All necessary imports are present.

The imports cover all essential packages needed for React testing with Vitest, including TypeScript path resolution and Node.js polyfills.


18-22: 🛠️ Refactor suggestion

Add coverage thresholds to maintain code quality.

Consider adding coverage thresholds to ensure maintaining the same code coverage standards that existed with Jest.

 coverage: {
   enabled: true,
   provider: 'istanbul',
   reporter: ['text', 'html', 'text-summary'],
+  lines: 80,
+  functions: 80,
+  branches: 80,
+  statements: 80,
 },
✅ Verification successful

Add coverage thresholds to match or exceed existing Jest thresholds

Based on the Jest configuration, the codebase previously had coverage thresholds of 20% for lines and statements. Consider adding equivalent or higher thresholds in the Vitest configuration:

 coverage: {
   enabled: true,
   provider: 'istanbul',
   reporter: ['text', 'html', 'text-summary'],
+  lines: 20,
+  statements: 20,
 },
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if Jest configuration has coverage thresholds
echo "Checking Jest configuration for coverage thresholds:"
rg -A 5 "coverageThreshold|collectCoverage" package.json jest.config.js jest.config.ts

Length of output: 797


15-15: Consider standardizing test file patterns.

The current pattern includes both .spec and .test extensions. For consistency during the migration from Jest to Vitest, it's recommended to standardize on one pattern, preferably .spec for Vitest tests.

✅ Verification successful

Standardizing test file patterns is recommended but requires careful migration

The codebase currently has a mix of .test (151 files) and .spec (2 files) patterns, with .test being the predominant convention. Given this distribution:

  • Most tests follow the .test pattern, suggesting it's the established convention
  • Only 2 files use .spec: constant.spec.ts and AddOn.spec.tsx

Recommend:

  • Standardize on .test pattern since it's already used by 98% of test files
  • Update the 2 .spec files to maintain consistency
  • Update vitest.config.ts to only include .test pattern to reflect the standardized convention
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check current test file patterns in the codebase
echo "Current test file patterns:"
fd -e test.tsx -e test.ts -e spec.tsx -e spec.ts . src/

Length of output: 11056

src/components/AddOn/AddOn.spec.tsx (1)

Line range hint 1-65: Successfully migrated to Vitest ✨

The test file has been successfully migrated from Jest to Vitest while:

  • Maintaining existing test coverage
  • Following the new .spec.tsx naming convention
  • Properly implementing Vitest mocking capabilities

src/vitest.test.tsx Outdated Show resolved Hide resolved
@palisadoes
Copy link
Contributor

Please make the changes so that coderabbit.ai approves the 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: 1

🧹 Outside diff range and nitpick comments (3)
src/vitest.test.tsx (3)

12-15: Remove unnecessary async keyword

The test doesn't contain any asynchronous operations, making the async keyword redundant.

-  it('should support DOM testing', async () => {
+  it('should support DOM testing', () => {
     render(<div data-testid="test">Hello</div>);
     expect(screen.getByTestId('test')).toBeInTheDocument();
   });

17-20: Enhance mocking test coverage

The test demonstrates basic mocking but could be expanded to cover more scenarios. Also, the async keyword is unnecessary.

-  it('should support mocking', async () => {
+  it('should support mocking', () => {
     const mock = vi.fn().mockReturnValue('mocked');
     expect(mock()).toBe('mocked');
+    
+    // Test spy functionality
+    const spy = vi.spyOn(console, 'log');
+    console.log('test');
+    expect(spy).toHaveBeenCalledWith('test');
+    
+    // Test mock implementation
+    const mockWithImpl = vi.fn().mockImplementation((x: number) => x * 2);
+    expect(mockWithImpl(2)).toBe(4);
   });

1-21: Plan for test file evolution

Since this is a temporary configuration validation file, consider:

  1. Adding a TODO comment indicating its temporary nature
  2. Creating a ticket to track its removal or evolution after the Jest to Vitest migration is complete
  3. Moving the configuration validation tests to a dedicated test utilities directory if they become permanent
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0fc12b2 and 565c161.

📒 Files selected for processing (1)
  • src/vitest.test.tsx (1 hunks)
🔇 Additional comments (1)
src/vitest.test.tsx (1)

1-4: LGTM! All necessary testing utilities are properly imported.

The imports cover all required dependencies for React components testing, DOM assertions, and Vitest utilities.

src/vitest.test.tsx Outdated Show resolved Hide resolved
@prayanshchh
Copy link
Author

named this commit suggestion #2 by mistake, sorry if it causes any confusion

@prayanshchh
Copy link
Author

@coderabbitai review

Copy link

coderabbitai bot commented Nov 23, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 23, 2024
@varshith257
Copy link
Member

Could you provide a video/image of latest coverage report on terminal of vitest for test has been migrated?

@prayanshchh
Copy link
Author

vitest.mp4

vitest.test.tsx file

mohamedrehan1 pushed a commit to mohamedrehan1/talawa-admin that referenced this pull request Dec 4, 2024
…ation#2457)

* configuring vitest

* migrating AddOn tests to vitest

* removing unnecessary alias

* eslint fix

* suggestion PalisadoesFoundation#2

* workflow setup

* fix: tsdoc workflow

* reformat comment to tsdoc fmt

* resolving jest, vitest workflow

* lint error

* add tsdoc comments

* exit for workflow

* format yml fix

* fixing workflow

* cleanup

* ts error

* Update .eslintignore

* tsconfig edit

* removing suggestions 2

* Update vitest.config.ts

* fmt

* config update

* ignoring .spec files for cov

* new suggestions

* merge reports

* Update vitest.config.ts

* vitest run fix

* report dir change

* report dir change 2

* check workflow

* workflow update

* fixing merge report

* suggestion reverted

* merge cov reports

* changing format of jest cov reports

* Merge Coverage Reports Using lcov-result-merger

* fixing merge report

* final changes

* final changes 2

---------

Co-authored-by: Vamshi Maskuri <[email protected]>
mohamedrehan1 pushed a commit to mohamedrehan1/talawa-admin that referenced this pull request Dec 4, 2024
…ation#2457)

* configuring vitest

* migrating AddOn tests to vitest

* removing unnecessary alias

* eslint fix

* suggestion PalisadoesFoundation#2

* workflow setup

* fix: tsdoc workflow

* reformat comment to tsdoc fmt

* resolving jest, vitest workflow

* lint error

* add tsdoc comments

* exit for workflow

* format yml fix

* fixing workflow

* cleanup

* ts error

* Update .eslintignore

* tsconfig edit

* removing suggestions 2

* Update vitest.config.ts

* fmt

* config update

* ignoring .spec files for cov

* new suggestions

* merge reports

* Update vitest.config.ts

* vitest run fix

* report dir change

* report dir change 2

* check workflow

* workflow update

* fixing merge report

* suggestion reverted

* merge cov reports

* changing format of jest cov reports

* Merge Coverage Reports Using lcov-result-merger

* fixing merge report

* final changes

* final changes 2

---------

Co-authored-by: Vamshi Maskuri <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
ignore-sensitive-files-pr The contributor has a legitimate reason for editiing protected files test Testing application
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants