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

Feature/upgrade testing #2335

Conversation

Kanishk-tiwari-045
Copy link

@Kanishk-tiwari-045 Kanishk-tiwari-045 commented Oct 14, 2024

What kind of change does this PR introduce?

Dependency upgrade for @testing-library/user-event from 12.8.3 to 14.5.2.

Issue Number:

Fixes #2072

Did you add tests for your changes?

No new tests added, as this is a dependency upgrade. Existing tests were checked.

Snapshots/Videos:

N/A

If relevant, did you update the documentation?

No documentation update required as this is a dependency update.

Summary:

This PR upgrades the @testing-library/user-event package from version 12.8.3 to 14.5.2.
The previous dependabot attempt failed due to compatibility issues, but this PR ensures that all dependencies are updated to work with the new version.

Does this PR introduce a breaking change?

No breaking changes expected, but as it's a major dependency upgrade, careful testing was performed.

Other information:

The rationale behind this update is to keep the package up to date with security fixes and performance improvements in version 14.5.2.

Have you read the contributing guide?

✅ Yes.

Summary by CodeRabbit

  • New Features

    • Added support for new dependencies to enhance testing capabilities.
  • Bug Fixes

    • Improved reliability of tests by ensuring asynchronous operations are properly awaited.
  • Documentation

    • Updated comments in configuration files for clarity.
  • Chores

    • Updated various dependencies in the package configuration for better performance and compatibility.

Copy link

Our Pull Request Approval Process

We have these basic policies to make the approval process smoother for our volunteer team.

Testing Your Code

Please make sure your code passes all tests. Our test code coverage system will fail if these conditions occur:

  1. The overall code coverage drops below the target threshold of the repository
  2. Any file in the pull request has code coverage levels below the repository threshold
  3. Merge conflicts

The process helps maintain the overall reliability of the code base and is a prerequisite for getting your PR approved. Assigned reviewers regularly review the PR queue and tend to focus on PRs that are passing.

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

@Kanishk-tiwari-045 Kanishk-tiwari-045 marked this pull request as ready for review October 14, 2024 08:55
Copy link
Contributor

coderabbitai bot commented Oct 14, 2024

Walkthrough

The pull request includes updates to configuration files and test suites. The .eslintignore file now ignores the src/components/ directory. The jest.config.js file has been modified to include whatwg-fetch and other minor adjustments. The package.json file has updated dependencies, including an upgrade of @testing-library/user-event to version 14.5.2. Additionally, numerous test files have been revised to enhance asynchronous handling, ensuring that userEvent interactions are awaited and assertions are consistent.

Changes

File(s) Change Summary
.eslintignore Added src/components/ to ignore list.
jest.config.js Updated setupFiles to use whatwg-fetch, added comments, and included a new line at the end.
package.json Updated dependencies: added @testing-library/dom, upgraded @testing-library/user-event to 14.5.2, updated @typescript-eslint/parser to 8.8.1, and added eslint with version 8.57.1.
src/App.test.tsx, src/components/.../*.test.tsx (multiple files) Enhanced asynchronous handling by adding await before userEvent interactions and updated assertions from toBeCalledWith to toHaveBeenCalledWith.

Assessment against linked issues

Objective Addressed Explanation
Upgrade @testing-library/user-event from 12.8.3 to 14.5.2 (#[2072])

Possibly related issues

Possibly related PRs

Suggested reviewers

  • palisadoes

🐇 In the code, we hop and play,
With tests and packages, we pave the way.
Dependencies updated, the components shine,
Asynchronous handling, all works just fine!
So let’s celebrate this code we adore,
With a hop and a skip, let’s code some more! 🐇


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.

Caution

Inline review comments failed to post

🛑 Comments failed to post (8)
.eslintignore (1)

2-3: 💡 Codebase verification

⚠️ Potential issue

Broad ESLint ignore rule for src/components/ introduces multiple risks

The addition of src/components/ to .eslintignore poses several concerns:

  1. Disables linting for all components:

    • With numerous subdirectories under src/components/, this rule will prevent ESLint from analyzing a large portion of the codebase.
    • Potential linting issues in these components will go unnoticed, leading to inconsistent code quality.
  2. Redundant specific ignore rule:

    • The specific ignore for tagTemplate.ts becomes unnecessary when the entire directory is ignored.
  3. Misaligned with PR objectives:

    • The change does not relate to upgrading the testing library and may have been inadvertently included.
🔗 Analysis chain

Reconsider broad ESLint ignore rule for components directory

The addition of src/components/ to .eslintignore raises some concerns:

  1. This broad rule ignores all files in the components directory, potentially leading to inconsistent code quality and hidden issues.
  2. It makes the more specific rule for tagTemplate.ts redundant.
  3. This change doesn't align with the PR objectives of upgrading the testing library.

Consider the following actions:

  1. Remove the src/components/ line if it's not absolutely necessary.
  2. Keep only the specific ignore rule for tagTemplate.ts.
  3. If ignoring the entire components directory is intentional, please provide a clear rationale for this decision and consider adding a comment explaining why.

To assess the impact of this change, let's check for any ESLint configuration files and the structure of the components directory:

This will help us understand if there are specific ESLint configurations for the components and the overall structure of the components directory.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for ESLint configuration files
echo "ESLint configuration files:"
fd -e js -e json -e yaml -e yml '\.eslint'

# Check the structure of the components directory
echo "Structure of src/components directory:"
fd . src/components -t d

Length of output: 3641

src/components/MemberRequestCard/MemberRequestCard.test.tsx (1)

82-83: 🛠️ Refactor suggestion

Consider adding error handling for asynchronous operations

While the changes to make user events asynchronous are excellent, it might be beneficial to add error handling for these asynchronous operations. This can help catch and report any unexpected issues during testing.

Consider wrapping the asynchronous operations in try-catch blocks. Here's an example of how you could modify the code:

try {
  await userEvent.click(screen.getByText(/Accept/i));
  await userEvent.click(screen.getByText(/Reject/i));
} catch (error) {
  console.error('Error during user event:', error);
  throw error; // Re-throw to fail the test
}

This approach would provide more detailed error information if an asynchronous operation fails, making it easier to debug issues in the future.

Also applies to: 112-113

src/screens/SubTags/SubTags.test.tsx (1)

4-4: 💡 Codebase verification

Incomplete Removal of Imports and Inconsistent Cache Merge Configuration Detected

The removal of waitForElementToBeRemoved and cleanup imports is not fully addressed:

  • cleanup is still used in multiple test files, which may cause lingering dependencies on these functions.
  • waitForElementToBeRemoved is present but commented out, indicating partial removal that might still affect test reliability.

Additionally, the merge function in cache configurations is inconsistently implemented:

  • ManageTag.test.tsx still uses the existing parameter.
  • SubTags.test.tsx has simplified the merge function by removing the existing parameter.

These inconsistencies can lead to unpredictable cache behavior and should be standardized across the codebase.

🔗 Analysis chain

Verify the impact of removed imports and simplified cache merge function.

The changes in the import statement and cache configuration appear to be part of the testing library upgrade. However, we should ensure that:

  1. The removal of waitForElementToBeRemoved and cleanup doesn't negatively impact other tests that might still rely on them.
  2. The simplification of the merge function in the cache configuration doesn't lead to unexpected behavior in how data is merged.

To check for any remaining usage of the removed imports, run:

Also, verify if the simplified merge function is consistent with other cache configurations:

Also applies to: 57-59

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of waitForElementToBeRemoved or cleanup
rg --type typescript 'waitForElementToBeRemoved|cleanup' src/

Length of output: 435


Script:

#!/bin/bash
# Search for other cache configurations with merge functions
rg --type typescript 'merge\s*\([^)]*\)\s*{' src/

Length of output: 157


Script:

#!/bin/bash
# Search for any remaining usage of waitForElementToBeRemoved or cleanup with PCRE2 enabled
rg --type typescript --pcre2 'waitForElementToBeRemoved|cleanup' src/

Length of output: 106


Script:

#!/bin/bash
# Search for other cache configurations with merge functions, corrected regex syntax
rg --type typescript 'merge\s*\([^)]*\)\s*\{' src/

Length of output: 87


Script:

#!/bin/bash
# Search for any remaining usage of waitForElementToBeRemoved or cleanup with correct file types
rg --type ts --type tsx 'waitForElementToBeRemoved|cleanup' src/

Length of output: 94


Script:

#!/bin/bash
# Search for other cache configurations with merge functions, corrected file types
rg --type ts --type tsx 'merge\s*\([^)]*\)\s*\{' src/

Length of output: 83


Script:

#!/bin/bash
# Search for any remaining usage of waitForElementToBeRemoved or cleanup in .ts and .tsx files
rg 'waitForElementToBeRemoved|cleanup' --glob '*.ts' --glob '*.tsx' src/

Length of output: 2275


Script:

#!/bin/bash
# Search for cache configurations with merge functions in .ts and .tsx files
rg 'merge\s*\([^)]*\)\s*\{' --glob '*.ts' --glob '*.tsx' src/

Length of output: 212

src/components/UserPortal/UserSidebarOrg/UserSidebarOrg.test.tsx (1)

337-337: ⚠️ Potential issue

Approve async update, but fix typo in variable name

The addition of await before userEvent.click() is correct and consistent with best practices. However, there's a typo in the variable name that should be corrected.

Please apply this change to fix the typo:

-    const peopelBtn = screen.getByTestId(/People/i);
-    await userEvent.click(peopelBtn);
+    const peopleBtn = screen.getByTestId(/People/i);
+    await userEvent.click(peopleBtn);

Committable suggestion was skipped due to low confidence.

src/screens/OrganizationEvents/OrganizationEvents.test.tsx (1)

338-359: ⚠️ Potential issue

Proper asynchronous handling, but duplicate code detected

The addition of await to userEvent.click() and userEvent.type() calls is correct and consistent with the @testing-library/user-event upgrade requirements. This ensures proper handling of asynchronous user interactions in the test suite.

However, there's a duplicate block of code for typing into the location input (lines 352-355 and 356-359). This duplication is likely unintentional and should be removed to maintain code cleanliness and prevent potential inconsistencies.

Please remove the duplicate block of code:

    await userEvent.type(
      screen.getByPlaceholderText(/Location/i),
      formData.location,
    );
-    await userEvent.type(
-      screen.getByPlaceholderText(/Location/i),
-      formData.location,
-    );
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

    await userEvent.click(screen.getByTestId('createEventModalBtn'));

    await waitFor(() => {
      expect(screen.getByPlaceholderText(/Enter Title/i)).toBeInTheDocument();
    });

    await userEvent.type(
      screen.getByPlaceholderText(/Enter Title/i),
      formData.title,
    );
    await userEvent.type(
      screen.getByPlaceholderText(/Enter Description/i),
      formData.description,
    );
    await userEvent.type(
      screen.getByPlaceholderText(/Location/i),
      formData.location,
    );
src/screens/Users/Users.test.tsx (1)

418-446: ⚠️ Potential issue

Reconsider removal of "search not found" test

A test case for "testing search not found" has been commented out. This scenario is important to test as it verifies the behavior when no results are found.

Consider one of the following actions:

  1. If the test is no longer relevant, remove it entirely.
  2. If the test is temporarily disabled, add a comment explaining why and when it should be re-enabled.
  3. If the functionality is still needed, update and reintegrate the test into the test suite.

Removing or disabling tests without clear reasons can lead to reduced test coverage and potential bugs in the future.

src/components/Advertisements/Advertisements.test.tsx (1)

766-775: 🛠️ Refactor suggestion

Good addition of infinite scroll test, but needs refinement.

The test case for infinite scroll is a valuable addition. However, there are a few points to improve:

  1. Remove the console.log statements. These are typically used for debugging and should not be in the final test code.
  2. The current implementation doesn't actually trigger a scroll event. You should simulate a scroll action to properly test the infinite scroll functionality.
  3. The assertion could be more specific about the expected number of items after scrolling.

Consider refactoring the test case as follows:

test('infinite scroll', async () => {
  // ... (previous setup code)

  // Get initial count of advertisement buttons
  let initialButtons = await screen.findAllByTestId('moreiconbtn');
  const initialCount = initialButtons.length;

  // Simulate a scroll event
  fireEvent.scroll(window, { target: { scrollY: 1000 } });

  // Wait for and get the new count of advertisement buttons
  await waitFor(async () => {
    const newButtons = await screen.findAllByTestId('moreiconbtn');
    expect(newButtons.length).toBeGreaterThan(initialCount);
  });
});

This implementation properly simulates a scroll event and makes a more specific assertion about the increase in the number of advertisements.

src/components/UsersTableItem/UserTableItem.test.tsx (1)

1333-1339: 🛠️ Refactor suggestion

Enhance change role test case

The test case for changing user roles can be improved:

  1. Add assertions to verify that the mutation was called with correct parameters.
  2. Test error handling for the mutation.
  3. Verify that the UI updates correctly after role change.

Here's an example of how you could enhance this test:

test('change role button should function properly', async () => {
  const user = userEvent.setup();
  const mockChangeMutation = jest.fn(() => ({ data: { changeUserRole: true } }));

  render(
    <MockedProvider mocks={[{ request: { query: CHANGE_USER_ROLE_MUTATION }, newData: mockChangeMutation }]}>
      <UsersTableItem {...props} />
    </MockedProvider>
  );

  const changeRoleBtn = screen.getByTestId('changeRoleInOrgabc');
  
  await user.selectOptions(changeRoleBtn, 'ADMIN');
  expect(mockChangeMutation).toHaveBeenCalledWith({ variables: { userId: '123', orgId: 'abc', role: 'ADMIN' } });
  
  await user.selectOptions(changeRoleBtn, 'USER');
  expect(mockChangeMutation).toHaveBeenCalledWith({ variables: { userId: '123', orgId: 'abc', role: 'USER' } });
  
  // Verify UI update
  expect(changeRoleBtn).toHaveValue('USER?abc');
  
  // Test error handling
  mockChangeMutation.mockImplementationOnce(() => { throw new Error('Change role failed'); });
  await user.selectOptions(changeRoleBtn, 'ADMIN');
  expect(screen.getByText(/Change role failed/i)).toBeInTheDocument();
});

This enhanced test provides better coverage and ensures proper error handling.

@Kanishk-tiwari-045
Copy link
Author

Kanishk-tiwari-045 commented Oct 14, 2024

WhatsApp Image 2024-10-11 at 17 49 17_4abb1814
WhatsApp Image 2024-10-11 at 17 49 14_3e70a310
@gautam-divyanshu Sir I'm almost there — just need to pass these 4 test suites, and everything should be working soon!
I am facing these specific errors like, data-testid, TobeInTheDocument, etc.

@palisadoes
Copy link
Contributor

Please fix the failing test

Copy link

This pull request did not get any activity in the past 10 days and will be closed in 180 days if no update occurs. Please verify it has no conflicts with the develop branch and rebase if needed. Mention it now if you need help or give permission to other people to finish your work.

@github-actions github-actions bot added the no-pr-activity No pull request activity label Oct 26, 2024
@palisadoes
Copy link
Contributor

Closing. Inactivity

@palisadoes palisadoes closed this Oct 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-pr-activity No pull request activity
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants