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 Facility Homepage Advance Filters Cypress Test #9105

Merged
merged 9 commits into from
Nov 13, 2024

Conversation

nihal467
Copy link
Member

@nihal467 nihal467 commented Nov 13, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a centralized utility for advanced filtering, improving the consistency and maintainability of filter interactions across various components.
    • Added new methods for selecting states, districts, local bodies, and facility types in the advanced filter utility.
  • Bug Fixes

    • Removed outdated methods related to advanced filtering to streamline functionality.
  • Refactor

    • Replaced direct calls to filter methods with calls to the new advanced filter utility, enhancing code organization.

@nihal467 nihal467 requested a review from a team as a code owner November 13, 2024 21:19
Copy link
Contributor

coderabbitai bot commented Nov 13, 2024

Walkthrough

The changes introduced in this pull request focus on refactoring the advanced filtering functionality across various Cypress test files. A new utility object, advanceFilters, has been created in advanceFilterHelpers.ts, consolidating methods for interacting with advanced filter elements. Existing test cases have been updated to utilize this new utility, replacing previous direct calls to page objects. Additionally, several methods related to advanced filtering have been removed from various page object classes, streamlining the codebase and enhancing maintainability.

Changes

File Path Change Summary
cypress/e2e/assets_spec/AssetHomepage.cy.ts Added import for advanceFilters, replaced assetFilters.clickadvancefilter() with advanceFilters.clickAdvancedFiltersButton().
cypress/e2e/facility_spec/FacilityCreation.cy.ts Added constant facilityType, replaced clickUpdateFacilityType("Primary Health Centres") with selectFacilityType(facilityType).
cypress/e2e/facility_spec/FacilityHomepage.cy.ts Added import for advanceFilters, replaced multiple direct calls to userPage and facilityPage with advanceFilters methods.
cypress/e2e/patient_spec/PatientHomepage.cy.ts Added import for advanceFilters, replaced patientHome.clickPatientAdvanceFilters() with advanceFilters.clickAdvancedFiltersButton().
cypress/e2e/shifting_spec/ShiftingAdvanceFilters.cy.ts Replaced shiftingPage.advancedFilterButton().click(); with advanceFilters.clickAdvancedFiltersButton();.
cypress/e2e/users_spec/UsersHomepage.cy.ts Added import for advanceFilters, replaced userPage.clickAdvancedFilters() with advanceFilters.clickAdvancedFiltersButton(), and updated other filter methods.
cypress/e2e/users_spec/UsersManage.cy.ts Added import for advanceFilters, replaced userPage.clickAdvancedFilters() with advanceFilters.clickAdvancedFiltersButton(), and updated other filter methods.
cypress/pageobject/Asset/AssetFilters.ts Removed method clickadvancefilter().
cypress/pageobject/Facility/FacilityCreation.ts Added selectFacilityType(facility: string), removed methods: clickUpdateFacilityType, selectState, selectDistrict, selectLocalBody.
cypress/pageobject/Patient/PatientHome.ts Removed method clickPatientAdvanceFilters().
cypress/pageobject/Shift/ShiftFilters.ts Removed method advancedFilterButton().
cypress/pageobject/Users/UserSearch.ts Removed methods: clickAdvancedFilters, applyFilter, clearFilters.
cypress/pageobject/utils/advanceFilterHelpers.ts Introduced new utility with methods for advanced filtering: clickAdvancedFiltersButton(), selectState(), selectDistrict(), selectLocalBody(), applySelectedFilter(), selectFacilityType(), clickClearAdvanceFilters().

Assessment against linked issues

Objective Addressed Explanation
Move existing Cypress facility advance filters to a helper function (9104)

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad

🐇 In the fields where rabbits roam,
Advanced filters now feel like home.
With a click and a hop, we streamline our way,
Making tests easier, come what may!
So let’s celebrate this code so bright,
With fluffy joy, we take flight! 🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

cypress/e2e/facility_spec/FacilityHomepage.cy.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

Error: Failed to load parser '@typescript-eslint/parser' declared in '.eslintrc.json': Cannot find module '@typescript-eslint/parser'
Require stack:

  • /.eslintrc.json
    at Module._resolveFilename (node:internal/modules/cjs/loader:1248:15)
    at Function.resolve (node:internal/modules/helpers:145:19)
    at Object.resolve (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2346:46)
    at ConfigArrayFactory._loadParser (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3325:39)
    at ConfigArrayFactory._normalizeObjectConfigDataBody (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3099:43)
    at _normalizeObjectConfigDataBody.next ()
    at ConfigArrayFactory._normalizeObjectConfigData (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3040:20)
    at _normalizeObjectConfigData.next ()
    at ConfigArrayFactory.loadInDirectory (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:2886:28)
    at CascadingConfigArrayFactory._loadConfigInAncestors (/node_modules/@eslint/eslintrc/dist/eslintrc.cjs:3871:46)

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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

netlify bot commented Nov 13, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 7850052
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/673530febc5b960008597f8f
😎 Deploy Preview https://deploy-preview-9105--care-ohc.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

@nihal467 nihal467 marked this pull request as draft November 13, 2024 21:19
Copy link

cloudflare-workers-and-pages bot commented Nov 13, 2024

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7850052
Status: ✅  Deploy successful!
Preview URL: https://b2d9e5d3.care-fe.pages.dev
Branch Preview URL: https://refactor-advancefilter.care-fe.pages.dev

View logs

@github-actions github-actions bot added needs-triage question Further information is requested labels Nov 13, 2024
@nihal467 nihal467 removed question Further information is requested needs-triage labels Nov 13, 2024
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: 7

🧹 Outside diff range and nitpick comments (13)
cypress/pageobject/utils/advanceFilterHelpers.ts (4)

1-29: Consider adding TypeScript interfaces for better type safety

The utility object is well-structured, but could benefit from explicit TypeScript interfaces to improve maintainability and type safety.

Consider adding an interface:

interface AdvanceFilters {
  clickAdvancedFiltersButton(): void;
  selectState(state: string): void;
  selectDistrict(district: string): void;
  selectLocalBody(localBody: string): void;
  applySelectedFilter(): void;
  selectFacilityType(facilityType: string): void;
  clickClearAdvanceFilters(): void;
}

export const advanceFilters: AdvanceFilters = {
  // ... existing implementation
};

2-4: Consider using more specific selectors

Using ID selectors is good, but consider using data-testid attributes for better test maintainability and to avoid conflicts with styling-related IDs.

-    cy.verifyAndClickElement("#advanced-filter", "Advanced Filters");
+    cy.verifyAndClickElement("[data-testid=advanced-filter-button]", "Advanced Filters");

1-29: Add tests for the utility methods

Consider adding tests for these utility methods to ensure they behave correctly across different scenarios.

Would you like me to help create a test file with example test cases for these utility methods? This could include:

  • Testing successful filter applications
  • Testing error scenarios
  • Testing hierarchical dependencies
  • Testing clear filter functionality

1-29: Add JSDoc documentation for better maintainability

Consider adding comprehensive JSDoc comments to improve code maintainability and usage understanding.

Example documentation:

/**
 * Utility object for managing advanced filters in facility-related tests
 */
export const advanceFilters = {
  /**
   * Clicks the advanced filters button to expand filter options
   * @example
   * advanceFilters.clickAdvancedFiltersButton();
   */
  clickAdvancedFiltersButton() {
    // ... implementation
  },
  
  /**
   * Selects a state from the state dropdown
   * @param state - The name of the state to select
   * @throws {Error} If the state is not found in the dropdown
   * @example
   * advanceFilters.selectState("California");
   */
  selectState(state: string) {
    // ... implementation
  },
  // ... other methods
};
cypress/e2e/shifting_spec/ShiftingAdvanceFilters.cy.ts (1)

Line range hint 20-57: Consider further centralization of filter operations

While the advanced filter button click has been centralized, the individual filtering operations (facility, category, date) are still using page-specific methods. Consider extending the advanceFilters utility to handle these common filtering patterns as well.

This would improve maintainability and reduce duplication across different page objects. For example:

// In advanceFilterHelpers.ts
export const advanceFilters = {
  // ... existing methods
  filterByFacility: (name: string, type: string, level: string) => {
    // Common implementation
  },
  filterByDate: (startDate: string, endDate: string, modifiedStart: string, modifiedEnd: string) => {
    // Common implementation
  }
};
cypress/e2e/users_spec/UsersHomepage.cy.ts (1)

Line range hint 33-60: Consider further refactoring for consistency

The test currently mixes direct userPage calls with advanceFilters utility methods. Consider moving all filter-related actions (like typeInFirstName, selectRole, etc.) to the advanceFilters utility for better consistency and maintainability.

Example refactoring:

-    userPage.typeInFirstName(firstName);
-    userPage.typeInLastName(lastName);
-    userPage.selectRole(role);
+    advanceFilters.setFirstName(firstName);
+    advanceFilters.setLastName(lastName);
+    advanceFilters.selectRole(role);
cypress/e2e/users_spec/UsersManage.cy.ts (2)

Line range hint 67-68: Replace hardcoded wait with proper wait strategy.

The comment "temporary hack to fix the failure" with cy.wait(5000) could make tests flaky. Consider using Cypress's built-in retry-ability:

-    cy.wait(5000); // temporary hack to fix the failure
+    // Wait for the specific condition that the hack was trying to handle
+    cy.get('[data-testid="linked-skills"]').should('exist');

Line range hint 8-186: Consider restructuring tests for better maintainability.

The test file could benefit from several improvements:

  1. Break down large test cases into smaller, focused ones following the Single Responsibility Principle
  2. Extract common patterns into shared helper functions
  3. Use before/beforeEach hooks more effectively to reduce setup duplication
  4. Consider using custom Cypress commands for common operations

Example structure:

describe('User Skills Management', () => {
  describe('Linking Skills', () => {
    it('should link a skill to a user')
    it('should reflect linked skill in user profile')
  })
  
  describe('Working Hours', () => {
    it('should validate working hours input')
    it('should update working hours')
    it('should reflect working hours in profile')
  })
})
cypress/e2e/patient_spec/PatientHomepage.cy.ts (2)

40-40: Consider further refactoring opportunities for filter-related methods.

While the clickAdvancedFiltersButton() has been standardized using the new advanceFilters utility, other filter-related methods (e.g., typePatientCreatedBeforeDate, selectFacilityType, etc.) are still using the page object directly. Consider moving these methods to the advanceFilters utility for better consistency and reusability.

Also applies to: 60-60, 78-78, 108-108, 120-120


Line range hint 40-57: Consider improving test maintainability and readability.

A few suggestions to enhance the test suite:

  1. Extract repeated verification patterns into custom commands or helper methods
  2. Move hardcoded test data (e.g., "Dummy Facility 40", "01122023") to test fixtures or constants
  3. Consider using data-driven tests for different filter combinations

Example custom command for filter verification:

// In commands.ts
Cypress.Commands.add('verifyAndClearFilters', (expectedCount: string) => {
  cy.clearAllFilters();
  cy.get('[data-cy="patient-count"]').should('contain', expectedCount);
});

Also applies to: 60-75, 78-117, 120-145

cypress/e2e/facility_spec/FacilityCreation.cy.ts (3)

60-60: LGTM! Consider centralizing test constants.

Moving the hardcoded facility type to a constant improves maintainability. If there are more similar constants across test files, consider moving them to a separate constants file.


289-289: LGTM! Consider enhancing update verification.

The facility type selection is correctly implemented in the update scenario. Consider adding assertions to verify that the facility type was actually updated.

 facilityPage.submitForm();
 cy.url().should("not.include", "/update");
+// Add assertion to verify facility type update
+facilityPage.getFacilityType().should("contain", facilityType);

Line range hint 1-324: Consider enhancing test organization and coverage.

While the test file is well-structured, consider these improvements:

  1. Move test constants to a separate file for better reusability across test files
  2. Add more assertions to verify facility type updates
  3. Consider using test data builders or factories to reduce test setup duplication
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7acc8be and 83753cf.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (13)
  • cypress/e2e/assets_spec/AssetHomepage.cy.ts (2 hunks)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (5 hunks)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (6 hunks)
  • cypress/e2e/shifting_spec/ShiftingAdvanceFilters.cy.ts (2 hunks)
  • cypress/e2e/users_spec/UsersHomepage.cy.ts (4 hunks)
  • cypress/e2e/users_spec/UsersManage.cy.ts (2 hunks)
  • cypress/pageobject/Asset/AssetFilters.ts (0 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (2 hunks)
  • cypress/pageobject/Patient/PatientHome.ts (0 hunks)
  • cypress/pageobject/Shift/ShiftFilters.ts (0 hunks)
  • cypress/pageobject/Users/UserSearch.ts (0 hunks)
  • cypress/pageobject/utils/advanceFilterHelpers.ts (1 hunks)
💤 Files with no reviewable changes (4)
  • cypress/pageobject/Asset/AssetFilters.ts
  • cypress/pageobject/Patient/PatientHome.ts
  • cypress/pageobject/Shift/ShiftFilters.ts
  • cypress/pageobject/Users/UserSearch.ts
🔇 Additional comments (20)
cypress/pageobject/utils/advanceFilterHelpers.ts (1)

1-29: Verify complete migration to new utility methods

Ensure all existing test files have been updated to use these new utility methods consistently.

✅ Verification successful

Let me check the actual content of these files to verify if they are using the old methods or have already been migrated.


Migration to new utility methods is complete

All files are already using the new advanceFilters utility methods consistently. No instances of old method names or direct selector usage were found in the test files. The implementation appears to be properly migrated across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct usage of the old selectors
rg -l "(#advanced-filter|#state|#district|#local_body|#facility_type)" cypress/e2e/

# Search for any remaining old method names that should have been migrated
rg -l "clickadvancefilter|clickUpdateFacilityType|clickPatientAdvanceFilters|clickAdvancedFilters" cypress/e2e/

Length of output: 478


Script:

#!/bin/bash
# Check the content of the files to see actual usage
for file in cypress/e2e/shifting_spec/ShiftingAdvanceFilters.cy.ts \
            cypress/e2e/users_spec/UsersHomepage.cy.ts \
            cypress/e2e/users_spec/UsersManage.cy.ts \
            cypress/e2e/patient_spec/PatientHomepage.cy.ts \
            cypress/e2e/assets_spec/AssetHomepage.cy.ts \
            cypress/e2e/facility_spec/FacilityHomepage.cy.ts; do
    echo "=== $file ==="
    rg -A 2 "(#advanced-filter|#state|#district|#local_body|#facility_type|clickadvancefilter|clickUpdateFacilityType|clickPatientAdvanceFilters|clickAdvancedFilters)" "$file"
done

Length of output: 5501

cypress/e2e/shifting_spec/ShiftingAdvanceFilters.cy.ts (2)

1-2: LGTM: Clean import structure

The addition of the advanceFilters utility import maintains good separation of concerns while keeping the existing page object import.


17-17: Verify consistent behavior across all filter scenarios

The switch to the centralized advanceFilters utility looks good. However, since this is a core setup step for all test cases, we should verify that the new utility method behaves identically to the previous implementation.

✅ Verification successful

Advanced filters implementation is consistent and properly centralized

The verification shows that:

  • The clickAdvancedFiltersButton is implemented in a centralized utility at cypress/pageobject/utils/advanceFilterHelpers.ts
  • It uses a consistent selector #advanced-filter with proper verification
  • All test files are using this centralized implementation
  • No old/direct button click implementations remain

The new utility method is being used consistently across all filter scenarios in different test suites (shifting, users, patients, assets, facility), and the implementation is properly abstracted using Cypress's built-in commands.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of the new advanceFilters utility across test files
# and verify no old implementation remains

# Check for any remaining direct usage of advancedFilterButton
rg -l "advancedFilterButton\(\)\.click\(\)" "cypress/e2e"

# Check adoption of new utility method
rg -l "advanceFilters\.clickAdvancedFiltersButton" "cypress/e2e"

Length of output: 401


Script:

#!/bin/bash
# Let's check the implementation of clickAdvancedFiltersButton in these files
# to ensure consistent behavior

# First, let's see the actual implementation of the utility method
rg -A 5 "clickAdvancedFiltersButton" "cypress/support" "cypress/pages"

# Then check how it's being used in test files
rg -B 2 -A 2 "clickAdvancedFiltersButton" "cypress/e2e"

Length of output: 5888


Script:

#!/bin/bash
# Let's check for the actual implementation of advanceFilters
# since it wasn't found in cypress/pages

# Search for the advanceFilters class/object definition
rg -A 10 "class.*advanceFilters|const.*advanceFilters" "cypress"

# Also check for any potential old implementations
rg -A 5 "advancedFilterButton" "cypress"

Length of output: 955

cypress/e2e/users_spec/UsersHomepage.cy.ts (3)

Line range hint 33-42: LGTM! Good refactoring of filter actions

The delegation of filter actions to the advanceFilters utility improves code organization and maintainability while maintaining the original test behavior.


Line range hint 60-67: LGTM! Clear filter refactoring looks good

The clear filter functionality has been successfully moved to the advanceFilters utility while maintaining all necessary verifications.


1-1: Verify the import path exists

The import of the new advanceFilters utility aligns with the refactoring goals. Let's verify the import path is correct.

✅ Verification successful

Import path is correctly configured

The import path pageobject/utils/advanceFilterHelpers is valid as the file exists at cypress/pageobject/utils/advanceFilterHelpers.ts relative to the repository root.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the advanceFilterHelpers file
fd "advanceFilterHelpers.ts" --type f

Length of output: 86

cypress/e2e/assets_spec/AssetHomepage.cy.ts (2)

1-1: LGTM! Import statement follows best practices.

The new import for advanceFilters is correctly placed and properly structured.


67-77: Enhance test coverage for filter functionality.

The current test verifies filter UI elements but lacks verification of the actual filtering results:

  1. Add assertions to verify filtered data:
it("should apply filters to asset list", () => {
  // Existing filter application
  cy.get('[data-testid="asset-list"]').within(() => {
    cy.get('[data-testid="asset-item"]').each(($el) => {
      cy.wrap($el).should('contain', 'Dummy Facility 40')
        .and('contain', 'ACTIVE')
        .and('contain', 'ONVIF Camera');
    });
  });
});
  1. Add negative test cases:
it("should handle invalid filter combinations gracefully", () => {
  // Test with non-existent facility
  // Test with incompatible asset class for facility
  // Test with invalid status
});

Let's verify the current test coverage:

cypress/e2e/users_spec/UsersManage.cy.ts (2)

1-2: LGTM! Clean import organization.

The new import follows good practices by:

  • Properly organizing utilities in a dedicated folder
  • Maintaining clear separation between utility and page object imports

60-63: LGTM! Verify consistent usage of advanceFilters utility.

The refactoring to use the centralized advanceFilters utility looks good. However, let's ensure consistency across all test cases.

✅ Verification successful

Let me check the actual usage in these files to determine if there are inconsistencies.


Let me check for any instances of applyFilter to ensure we haven't missed any occurrences that should be using applySelectedFilter.


Let me check for the new applySelectedFilter method to ensure it's being used consistently.


The refactoring is consistently applied across test files

Based on the verification results, both UsersHomepage.cy.ts and UsersManage.cy.ts are consistently using the new advanceFilters utility with clickAdvancedFiltersButton() and applySelectedFilter() methods. No instances of the old methods were found, confirming the refactoring was thorough.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining direct filter interactions that should use the utility
rg -l "clickAdvancedFilters|applyFilter|clearFilters" "cypress/e2e/users_spec/"

Length of output: 163


Script:

#!/bin/bash
# Check the actual usage of these methods in both files
rg "clickAdvancedFilters|applyFilter|clearFilters" "cypress/e2e/users_spec/UsersManage.cy.ts" "cypress/e2e/users_spec/UsersHomepage.cy.ts" -B 2 -A 2

Length of output: 1113


Script:

#!/bin/bash
# Search specifically for applyFilter variations
rg "applyFilter" "cypress/e2e/users_spec/" -B 2 -A 2

Length of output: 50


Script:

#!/bin/bash
# Search for applySelectedFilter
rg "applySelectedFilter" "cypress/e2e/users_spec/" -B 2 -A 2

Length of output: 951

cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3)

9-9: LGTM: Clean import of the new utility.

The import follows the established pattern and is correctly referenced.


65-70: LGTM: Clean refactoring to use centralized filter utility.

The migration to advanceFilters utility improves code organization by centralizing filter operations while maintaining clear verification steps.


121-125: LGTM: Consistent implementation of filter operations.

The refactoring maintains consistency with the previous usage pattern and preserves test readability.

cypress/e2e/patient_spec/PatientHomepage.cy.ts (2)

1-2: LGTM! Import changes align with the refactoring effort.

The addition of the advanceFilters utility import is consistent with the refactoring goals.


Line range hint 40-145: Verify error handling for filter operations.

The tests should verify error scenarios such as:

  • Invalid date ranges
  • Invalid age ranges
  • Non-existent facility names
  • Network failures during filter operations
cypress/e2e/facility_spec/FacilityCreation.cy.ts (2)

121-121: LGTM! Method name better reflects its purpose.

The updated method name selectFacilityType better describes the action being performed compared to the previous clickUpdateFacilityType.


210-210: LGTM! Consistent usage across test scenarios.

The facility type selection is consistently implemented across different facility creation scenarios, maintaining good test structure.

Also applies to: 250-250

cypress/pageobject/Facility/FacilityCreation.ts (3)

1-1: LGTM! Good practice to centralize advanced filter functionality.

The import of advanceFilters utility aligns with the refactoring goal of centralizing filter-related functionality, improving maintainability.


17-19: LGTM! Clean delegation to the utility method.

The implementation follows good practices by:

  • Providing a clean interface to the underlying utility
  • Following the single responsibility principle

Line range hint 1-22: Verify complete migration to advanceFilters utility.

Several methods were removed as part of this refactoring. Let's verify that all removed methods are properly handled by the advanceFilters utility and that there are no remaining references to the removed methods.

#!/bin/bash
# Search for any remaining references to removed methods
echo "Searching for references to removed methods..."
rg -t ts "clickUpdateFacilityType|selectState|selectDistrict|selectLocalBody" cypress/

# Verify the implementation of corresponding methods in advanceFilters
echo "Verifying advanceFilters implementation..."
rg -t ts "selectFacilityType|selectState|selectDistrict|selectLocalBody" cypress/pageobject/utils/advanceFilterHelpers.ts

Comment on lines +6 to +16
selectState(state: string) {
cy.clickAndSelectOption("#state", state);
},

selectDistrict(district: string) {
cy.clickAndSelectOption("#district", district);
},

selectLocalBody(localBody: string) {
cy.clickAndSelectOption("#local_body", localBody);
},
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

Add validation for hierarchical filter dependencies

The state, district, and local body selections are hierarchically dependent, but the methods don't verify if the parent selection exists before allowing child selection.

Consider implementing validation:

selectDistrict(district: string) {
  // Verify state is selected before allowing district selection
  cy.get("#state").should("have.value.not.eq", "");
  cy.clickAndSelectOption("#district", district);
},

selectLocalBody(localBody: string) {
  // Verify district is selected before allowing local body selection
  cy.get("#district").should("have.value.not.eq", "");
  cy.clickAndSelectOption("#local_body", localBody);
},

Comment on lines 1 to 29
export const advanceFilters = {
clickAdvancedFiltersButton() {
cy.verifyAndClickElement("#advanced-filter", "Advanced Filters");
},

selectState(state: string) {
cy.clickAndSelectOption("#state", state);
},

selectDistrict(district: string) {
cy.clickAndSelectOption("#district", district);
},

selectLocalBody(localBody: string) {
cy.clickAndSelectOption("#local_body", localBody);
},

applySelectedFilter() {
cy.verifyAndClickElement("#apply-filter", "Apply");
},

selectFacilityType(facilityType: string) {
cy.clickAndSelectOption("#local_body", facilityType);
},

clickClearAdvanceFilters() {
cy.verifyAndClickElement("#clear-filter", "Clear");
},
};
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

Enhance error handling and timeout management

The methods should handle common test scenarios like failed selections or slow-loading dropdowns.

Consider adding timeout and error handling:

selectState(state: string) {
  cy.get("#state", { timeout: 10000 })
    .should("be.visible")
    .then($select => {
      if ($select.find(`option:contains("${state}")`).length === 0) {
        throw new Error(`State "${state}" not found in dropdown`);
      }
      cy.clickAndSelectOption("#state", state);
    });
},

Comment on lines 22 to 24
selectFacilityType(facilityType: string) {
cy.clickAndSelectOption("#local_body", facilityType);
},
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect selector in selectFacilityType method

The method is currently using the wrong selector (#local_body) which is meant for local body selection. This will cause the facility type selection to fail.

-    cy.clickAndSelectOption("#local_body", facilityType);
+    cy.clickAndSelectOption("#facility_type", facilityType);
📝 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.

Suggested change
selectFacilityType(facilityType: string) {
cy.clickAndSelectOption("#local_body", facilityType);
},
selectFacilityType(facilityType: string) {
cy.clickAndSelectOption("#facility_type", facilityType);
},

Comment on lines +69 to +75
advanceFilters.clickAdvancedFiltersButton();
assetFilters.clickslideoverbackbutton(); // to verify the back button doesn't clear applied filters
assetFilters.assertFacilityText("Dummy Facility 40");
assetFilters.assertAssetClassText("ONVIF");
assetFilters.assertStatusText("ACTIVE");
assetFilters.assertLocationText("Camera Loc");
assetFilters.clickadvancefilter();
advanceFilters.clickAdvancedFiltersButton();
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

Improve test maintainability and reliability.

While the refactoring to use advanceFilters is good, there are several areas for improvement:

  1. Standardize method naming conventions:
- assetFilters.clickslideoverbackbutton();
+ assetFilters.clickSlidingPanelBackButton();
  1. Extract test data to constants or fixtures:
+ const TEST_FILTERS = {
+   facility: "Dummy Facility 40",
+   status: "ACTIVE",
+   assetClass: "ONVIF Camera",
+   location: "Camera Loc"
+ };

  assetFilters.filterAssets(
-   "Dummy Facility 40",
-   "ACTIVE",
-   "ONVIF Camera",
-   "Camera Loc",
+   TEST_FILTERS.facility,
+   TEST_FILTERS.status,
+   TEST_FILTERS.assetClass,
+   TEST_FILTERS.location,
  );
  1. Add explicit waits for filter operations:
  advanceFilters.clickAdvancedFiltersButton();
+ cy.wait('@getFilteredAssets');  // Add corresponding route intercept
  assetFilters.clickSlidingPanelBackButton();
  1. Split the test into smaller, focused test cases:
it("should persist filters after closing sliding panel", () => {
  // Test filter persistence
});

it("should display correct filter badges", () => {
  // Test filter badges
});

it("should clear all filters", () => {
  // Test filter clearing
});

facilityPage.verifyStateBadgeContent(stateName);
facilityPage.verifyDistrictBadgeContent(district);
facilityPage.verifyLocalBodyBadgeContent(localBody);
facilityPage.verifyFacilityTypeBadgeContent(facilityType);
manageUserPage.assertFacilityInCard(facilityName);
userPage.clearFilters();
advanceFilters.applySelectedFilter();
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove redundant filter application.

This line appears to be a duplicate call to applySelectedFilter() which was already called on line 70.

-    advanceFilters.applySelectedFilter();
📝 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.

Suggested change
advanceFilters.applySelectedFilter();

@@ -6,6 +6,7 @@
import LoginPage from "../../pageobject/Login/LoginPage";
import ManageUserPage from "../../pageobject/Users/ManageUserPage";
import { UserPage } from "../../pageobject/Users/UserSearch";
import { advanceFilters } from "../../pageobject/utils/advanceFilterHelpers";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the results, I can now generate the final response:

Migration to advanceFilters utility is incomplete

Several components still contain direct filter operations that should be migrated to the centralized utility:

  • cypress/pageobject/Users/UserSearch.ts: Contains direct implementations of selectState and selectDistrict
  • cypress/pageobject/Patient/PatientHome.ts: Contains direct implementation of selectFacilityType
  • cypress/pageobject/Facility/FacilityCreation.ts: Contains multiple direct filter operations including selectFacilityType, selectStateOnPincode, selectDistrictOnPincode

These implementations should be migrated to the advanceFilterHelpers utility to maintain consistency and reduce code duplication.

🔗 Analysis chain

Verify test coverage and migration completeness.

Since this is part of a larger refactoring effort to standardize filter operations, let's verify:

  1. Test coverage for the new advanceFilters utility
  2. Any remaining direct filter operations that should be migrated
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test coverage and remaining direct filter operations

# Check for test coverage of the new utility
echo "Checking for test coverage of advanceFilterHelpers..."
rg -l "advanceFilterHelpers" cypress/e2e/**/*spec.ts

# Look for potential remaining direct filter operations that should be migrated
echo "Checking for potential remaining direct filter operations..."
rg -A 2 "clickAdvancedFilters|selectState|selectDistrict|selectLocalBody|selectFacilityType" \
   --type ts \
   --glob '!**/advanceFilterHelpers.ts' \
   --glob '!**/FacilityHomepage.cy.ts'

Length of output: 9046

advanceFilters.selectFacilityType(facility);
}

selectLocalBody;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Critical: Implement selectLocalBody method to match its usage in tests

The incomplete selectLocalBody declaration in FacilityCreation.ts needs implementation as it's actively used in multiple test files:

  • cypress/e2e/patient_spec/PatientRegistration.cy.ts
  • cypress/pageobject/Patient/PatientPredefined.ts
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts

Implement it to delegate to advanceFilters.selectLocalBody() which exists in cypress/pageobject/utils/advanceFilterHelpers.ts:

-  selectLocalBody;
+  selectLocalBody(localBody: string) {
+    advanceFilters.selectLocalBody(localBody);
+  }
🔗 Analysis chain

Critical: Incomplete method declaration needs implementation.

The selectLocalBody declaration appears to be incomplete, which could lead to runtime errors if called. This seems to be part of the refactoring where the original method was removed.

Let's verify the usage of this method in tests:

Consider one of these implementations based on your needs:

-  selectLocalBody;
+  selectLocalBody(localBody: string) {
+    advanceFilters.selectLocalBody(localBody);
+  }

Or remove it if it's no longer needed:

-  selectLocalBody;
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for calls to selectLocalBody in test files
rg -t ts "selectLocalBody" cypress/e2e/

Length of output: 3440

Copy link

cypress bot commented Nov 13, 2024

CARE    Run #3913

Run Properties:  status check passed Passed #3913  •  git commit 78500528d2: Refactor Facility Homepage Advance Filters
Project CARE
Branch Review refactor-advancefilter
Run status status check passed Passed #3913
Run duration 04m 45s
Commit git commit 78500528d2: Refactor Facility Homepage Advance Filters
Committer Mohammed Nihal
View all properties for this run ↗︎

Test results
Tests that failed  Failures 0
Tests that were flaky  Flaky 0
Tests that did not run due to a developer annotating a test with .skip  Pending 0
Tests that did not run due to a failure in a mocha hook  Skipped 0
Tests that passed  Passing 126
View all changes introduced in this branch ↗︎

@nihal467 nihal467 marked this pull request as ready for review November 13, 2024 23:15
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (2)

76-77: Optimize filter clearing operation

The advanced filters button is clicked again just to clear the filters. Consider removing this redundant step since the filters panel should already be open from the previous operations.

-    advanceFilters.clickAdvancedFiltersButton();
     advanceFilters.clickClearAdvanceFilters();

9-9: Track remaining filter migration work

While this file successfully implements the new advanceFilters utility, there are still components that need migration:

  • cypress/pageobject/Users/UserSearch.ts
  • cypress/pageobject/Patient/PatientHome.ts
  • cypress/pageobject/Facility/FacilityCreation.ts

Consider creating tracking issues for migrating these components to maintain consistency across the codebase.

Would you like me to create GitHub issues to track the remaining migration work?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 83753cf and 7850052.

📒 Files selected for processing (4)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/e2e/users_spec/UsersHomepage.cy.ts (4 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (2 hunks)
  • cypress/pageobject/utils/advanceFilterHelpers.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cypress/e2e/users_spec/UsersHomepage.cy.ts
  • cypress/pageobject/utils/advanceFilterHelpers.ts
🔇 Additional comments (6)
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3)

9-9: LGTM! Import of centralized filter utility

The import of advanceFilters aligns with the PR objective of centralizing filter operations.


65-70: LGTM! Well-structured filter application sequence

The filter application follows a clear and logical sequence using the new centralized utility.


121-125: LGTM! Consistent filter implementation

The filter application follows the same pattern established earlier, maintaining consistency throughout the test file.

cypress/pageobject/Facility/FacilityCreation.ts (3)

1-1: LGTM: Import statement aligns with refactoring goals

The import of advanceFilters from the helper file supports the PR objective of moving advance filters to a dedicated helper.


21-23: LGTM: Implements selectLocalBody as suggested

The implementation correctly delegates to the helper function and addresses the past review comment about implementing selectLocalBody.


17-19: Verify usage of new selectFacilityType method

The method correctly delegates to the helper function and improves naming clarity over the old clickUpdateFacilityType.

✅ Verification successful

Method migration is complete and consistent

The verification shows that:

  • No instances of the old clickUpdateFacilityType method remain in the codebase
  • The new selectFacilityType method is properly used across multiple test files and page objects
  • The implementation is consistent with the string parameter type across all usages
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all occurrences of clickUpdateFacilityType have been replaced with selectFacilityType

# Search for any remaining usage of old method
echo "Checking for any remaining usage of clickUpdateFacilityType:"
rg "clickUpdateFacilityType" 

# Search for usage of new method to confirm migration
echo "Checking usage of new selectFacilityType method:"
rg "selectFacilityType"

Length of output: 1256

@khavinshankar khavinshankar merged commit da5d576 into develop Nov 13, 2024
57 checks passed
@khavinshankar khavinshankar deleted the refactor-advancefilter branch November 13, 2024 23:53
Copy link

@nihal467 Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

@nihal467 nihal467 changed the title Refactor Facility Homepage Advance Filters Refactor Facility Homepage Advance Filters Cypress Test Nov 19, 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.

Move Existing Cypress Facility advance filters to a helper function
2 participants