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 Export & Add New Sidebar collapse & expand Test #9066

Open
wants to merge 11 commits into
base: develop
Choose a base branch
from

Conversation

Alokih
Copy link
Contributor

@Alokih Alokih commented Nov 8, 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

  • New Features

    • Introduced a test case to verify the sidebar's collapse and expand functionality.
    • Enhanced sidebar interaction with new methods for toggling and verifying visibility of icons and text.
  • Improvements

    • Added data-testid attributes to components for better testability.
    • Streamlined CSV download functionality tests to include capacity exports.
  • Bug Fixes

    • Ensured local storage is saved after each test execution.

@Alokih Alokih requested a review from a team as a code owner November 8, 2024 17:23
Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

Walkthrough

The pull request introduces modifications to the Cypress end-to-end test suite for the facility homepage, including the addition of a sidebar collapse and expand functionality test. Enhancements to the FacilityHome class allow for improved sidebar interactions. The existing capacity export functionality has been integrated into the facility export test. Additionally, new data-testid attributes have been added to various components to enhance testability.

Changes

File Path Change Summary
cypress/e2e/facility_spec/FacilityHomepage.cy.ts Added sidebar collapse/expand test, integrated capacity export into facility export test, moved afterEach hook.
cypress/pageobject/Facility/FacilityHome.ts Added methods for sidebar interactions: toggleSidebar(), verifyIconsAndTextVisible(), verifyIconsVisibleAndTextHidden(), and new selectors for sidebar elements.
src/components/Common/Sidebar/Sidebar.tsx Added data-testid="sidebar-toggle" to the button element in ToggleShrink.
src/components/Common/Sidebar/SidebarItem.tsx Added data-testid attributes to div and span for sidebar icon and text in SidebarItemBase.

Assessment against linked issues

Objective Addressed Explanation
Refactor the existing facility export and add test for sidebar collapse (9043)
Verify sidebar functionality: icons/text visibility when collapsed/expanded (9043)
Integrate capacity export into facility export functionality (9043)

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • nihal467
  • khavinshankar

Poem

In the land of tests, where bunnies play,
The sidebar toggles in a joyful way.
With icons shining bright and texts that hide,
Our Cypress tests now take a grand ride!
So hop along, dear friends, and see,
How smoothly our features now can be! 🐇✨

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)

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3d06dba and 9d65b4f.

📒 Files selected for processing (1)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts

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 8, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 9d65b4f
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6738958310b28e0008eeb203
😎 Deploy Preview https://deploy-preview-9066--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.

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/pageobject/Facility/FacilityHome.ts (1)

7-9: Consider maintaining consistent selector patterns across the class.

While the new selectors correctly use data-testid attributes (which is great for test stability), they differ in style from existing selectors in the class. Consider either:

  1. Converting all selectors to arrow functions (preferred for preventing stale elements), or
  2. Maintaining consistency with existing string property pattern
-  sidebarToggle = () => cy.get('[data-testid="sidebar-toggle"]');
-  sidebarIcon = () => cy.get('[data-testid="sidebar-icon"]');
-  sidebarText = () => cy.get('[data-testid="sidebar-text"]');
+  // Option 1 (Preferred): Convert all selectors to arrow functions
+  exportButton = () => cy.get("#export-button");
+  sidebarToggle = () => cy.get('[data-testid="sidebar-toggle"]');
+  sidebarIcon = () => cy.get('[data-testid="sidebar-icon"]');
+  sidebarText = () => cy.get('[data-testid="sidebar-text"]');
+
+  // OR Option 2: Keep consistent with current pattern
+  sidebarToggle = '[data-testid="sidebar-toggle"]';
+  sidebarIcon = '[data-testid="sidebar-icon"]';
+  sidebarText = '[data-testid="sidebar-text"]';
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (1)

139-152: Enhance test readability with descriptive steps.

The test implementation looks good and covers all required scenarios. Consider adding cy.log() statements to make the test steps more descriptive and easier to debug.

 it("Verify sidebar collapse and expand functionality", () => {
+    cy.log('Verify initial sidebar state');
     facilityHome.toggleSidebar();
     facilityHome.verifyIconsVisible();
     facilityHome.verifyTextVisible();
 
-    // Click toggle button to collapse sidebar, verify icons visible and text hidden
+    cy.log('Verify collapsed sidebar state');
     facilityHome.toggleSidebar();
     facilityHome.verifyIconsVisible();
     facilityHome.verifyTextHidden();
 
-    // Click toggle button again to expand sidebar, verify icons and text are visible again
+    cy.log('Verify expanded sidebar state');
     facilityHome.toggleSidebar();
     facilityHome.verifyIconsVisible();
     facilityHome.verifyTextVisible();
   });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 66ef112 and 9ad063c.

📒 Files selected for processing (4)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (4 hunks)
  • cypress/pageobject/Facility/FacilityHome.ts (2 hunks)
  • src/components/Common/Sidebar/Sidebar.tsx (1 hunks)
  • src/components/Common/Sidebar/SidebarItem.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Common/Sidebar/Sidebar.tsx
🔇 Additional comments (8)
cypress/pageobject/Facility/FacilityHome.ts (2)

111-113: LGTM! Clean and focused implementation.

The toggleSidebar method is simple and follows the single responsibility principle.


115-129: Consider enhancing visibility verification methods.

While the implementation is functional, consider these improvements:

  1. Add timeout configuration for visibility checks
  2. Add error handling for missing elements
  3. Consider combining similar verification methods using a parameter
-  verifyIconsVisible() {
-    this.sidebarIcon().each(($el) => {
-      cy.wrap($el).should("be.visible");
-    });
-  }
-
-  verifyTextVisible() {
-    this.sidebarText().each(($el) => {
-      cy.wrap($el).should("be.visible");
-    });
-  }
+  verifySidebarElementsVisibility(elementType: 'icon' | 'text', shouldBeVisible: boolean = true) {
+    const selector = elementType === 'icon' ? this.sidebarIcon : this.sidebarText;
+    const assertion = shouldBeVisible ? 'be.visible' : 'not.be.visible';
+    
+    selector()
+      .should('exist')
+      .should(assertion, { timeout: 10000 })
+      .then($elements => {
+        if ($elements.length === 0) {
+          throw new Error(`No ${elementType} elements found in sidebar`);
+        }
+      });
+  }

This refactored version:

  • Combines similar methods into one configurable method
  • Adds timeout for flaky test prevention
  • Verifies elements exist before checking visibility
  • Provides better error messages
src/components/Common/Sidebar/SidebarItem.tsx (3)

63-65: LGTM! Well-placed test identifier for the sidebar icon.

The data-testid="sidebar-icon" attribute is appropriately placed on the icon container, making it easily targetable in the new sidebar collapse/expand tests.


67-67: LGTM! Well-placed test identifier for the sidebar text.

The data-testid="sidebar-text" attribute is correctly added to the text container span, enabling proper visibility testing when the sidebar is collapsed/expanded.


Line range hint 52-57: Verify resetHistory functionality as noted in the comment.

There's a comment suggesting to check if resetHistory is working as intended. Let's verify its usage across the codebase.

✅ Verification successful

Let me gather more context about the useAppHistory hook and its implementation to better understand the resetHistory functionality.


Let me search for the context and implementation of the history-related contexts to understand the complete flow.


resetHistory functionality is correctly implemented and used

The verification shows that resetHistory is properly implemented and used in the SidebarItem component:

  • It's correctly imported from useAppHistory hook
  • The hook properly connects to the ResetHistoryContext from HistoryAPIProvider
  • It's called in the onClick handler along with other navigation-related callbacks
  • The implementation follows React's context pattern for history management

The comment "On Review: Check if resetHistory is working as intended" can be safely removed as the functionality is verified.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for resetHistory usage and implementation
echo "Searching for resetHistory implementation..."
ast-grep --pattern 'const { resetHistory } = useAppHistory()' -A 10

echo "\nSearching for resetHistory usage..."
rg 'resetHistory\(' -A 5

Length of output: 1677


Script:

#!/bin/bash
# Search for useAppHistory implementation
echo "Searching for useAppHistory implementation..."
ast-grep --pattern 'function useAppHistory()' -A 15

echo "\nSearching for useAppHistory hook definition..."
rg 'export.*useAppHistory' -A 10

echo "\nSearching for AppHistory type or interface..."
rg 'type.*AppHistory|interface.*AppHistory' -A 5

Length of output: 1157


Script:

#!/bin/bash
# Search for HistoryContext and ResetHistoryContext
echo "Searching for History contexts..."
rg "HistoryContext|ResetHistoryContext" -A 5

echo "\nSearching for history provider implementation..."
ast-grep --pattern 'function HistoryProvider' -A 15

echo "\nSearching for resetHistory usage in the component..."
rg "resetHistory" src/components/Common/Sidebar/SidebarItem.tsx -A 5 -B 5

Length of output: 3149

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

2-3: LGTM: Import changes and new capacity alias.

The addition of the capacitiesAlias constant aligns with the PR objective of integrating capacity export functionality into the main facility export test.

Also applies to: 19-19


156-158: LGTM: afterEach hook relocation.

The relocation of the afterEach hook to the end of the file is a good organizational change and maintains the correct functionality.


111-115: 🛠️ Refactor suggestion

Add API verification for capacity export.

While the integration of capacity export test looks good, the PR objectives mention adding API verification to enhance test reliability. Consider adding API checks to verify the exported data.

Example implementation:

// Verify Capacity Export
facilityHome.csvDownloadIntercept(capacitiesAlias, "&capacity");
// Add API verification before download
cy.request('GET', '/api/v1/facility/capacity').then((response) => {
  expect(response.status).to.eq(200);
  const apiData = response.body;
  
  facilityHome.clickExportButton();
  facilityHome.clickMenuItem("Capacities");
  
  // Verify downloaded CSV matches API data
  facilityHome.verifyDownload(capacitiesAlias).then((csvData) => {
    expect(csvData).to.deep.equal(apiData);
  });
});

Copy link
Contributor

@Jacobjeevan Jacobjeevan left a comment

Choose a reason for hiding this comment

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

LGTM

@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Nov 11, 2024
Copy link

👋 Hi, @Alokih,
Conflicts have been detected against the base branch. Please rebase your branch against the base branch.


This message is automatically generated by prince-chrismc/label-merge-conflicts-action so don't hesitate to report issues/improvements there.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

141-156: Consider verifying initial sidebar state.

While the test effectively verifies collapse and expand functionality, consider adding assertions to verify the initial state of the sidebar before any interactions.

 it("Verify sidebar collapse and expand functionality", () => {
+    // Verify initial state
+    facilityHome.verifyIconsVisible();
+    facilityHome.verifyTextVisible();
+
     facilityHome.toggleSidebar();
     facilityHome.verifyIconsVisible();
     facilityHome.verifyTextVisible();
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9ad063c and eb07939.

📒 Files selected for processing (3)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (4 hunks)
  • cypress/pageobject/Facility/FacilityHome.ts (2 hunks)
  • src/components/Common/Sidebar/SidebarItem.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cypress/pageobject/Facility/FacilityHome.ts
  • src/components/Common/Sidebar/SidebarItem.tsx
🧰 Additional context used
🪛 Biome
cypress/e2e/facility_spec/FacilityHomepage.cy.ts

[error] 209-209: expected } but instead the file ends

the file ends here

(parse)


[error] 206-209: Disallow duplicate setup and teardown hooks.

Disallow afterEach duplicacy inside the describe function.

(lint/suspicious/noDuplicateTestHooks)

🔇 Additional comments (2)
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (2)

21-21: LGTM: Consistent constant naming.

The new capacitiesAlias follows the established naming pattern for CSV download aliases.


113-117: LGTM: Clean integration of capacity export test.

The capacity export verification follows the established pattern and successfully integrates with the facility export test as per PR objectives.

✅ Verification successful

The previous search was too specific. Let's broaden our search patterns to find any capacity export related tests that might still exist separately.


Integration of capacity export test verified - no duplicate tests found

The search results confirm that the capacity export test exists only in FacilityHomepage.cy.ts and there are no separate or duplicate capacity export tests remaining in the codebase. The integration is clean and follows the consolidated approach as intended.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify no remaining separate capacity export tests
rg -l "Verify Capacity Export Functionality" --type ts

Length of output: 56


Script:

#!/bin/bash
# Search for any capacity export related tests with broader patterns
rg -i "capacity.*export" --type ts

# Also check for any test descriptions mentioning capacity exports
rg -i "describe.*capacity.*export" --type ts
rg -i "it.*capacity.*export" --type ts

# Look for any cy.intercept calls related to capacity
ast-grep --pattern 'cy.intercept($$$capacity$$$)'

Length of output: 255

Comment on lines 207 to 209
afterEach(() => {
cy.saveLocalStorage();
});
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 duplicate afterEach hook.

There's a duplicate afterEach hook outside the describe block. This is redundant as the same hook already exists within the describe block and could lead to unexpected behavior.

Remove the duplicate hook:

-afterEach(() => {
-  cy.saveLocalStorage();
-});
📝 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
afterEach(() => {
cy.saveLocalStorage();
});
🧰 Tools
🪛 Biome

[error] 209-209: expected } but instead the file ends

the file ends here

(parse)


[error] 206-209: Disallow duplicate setup and teardown hooks.

Disallow afterEach duplicacy inside the describe function.

(lint/suspicious/noDuplicateTestHooks)

@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Nov 11, 2024
it("Verify sidebar collapse and expand functionality", () => {
facilityHome.toggleSidebar();
facilityHome.verifyIconsVisible();
facilityHome.verifyTextVisible();
Copy link
Member

Choose a reason for hiding this comment

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

  • it does not verify that each icon has a respective text next to it.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@nihal467 sir I have made changes for this & sorry for those syntax & duplicate errors I tried to fix merge conflicts directly & made those mistakes

facilityHome.toggleSidebar();
facilityHome.verifyIconsVisible();
facilityHome.verifyTextVisible();

Copy link
Member

Choose a reason for hiding this comment

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

  • once the test is complete, the brackets are missing, syntax error

@@ -185,3 +203,7 @@ describe("Facility Homepage Function", () => {
cy.saveLocalStorage();
});
});

afterEach(() => {
Copy link
Member

Choose a reason for hiding this comment

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

  • delete the duplicate aftereach function

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

🧹 Outside diff range and nitpick comments (1)
cypress/pageobject/Facility/FacilityHome.ts (1)

7-8: Maintain consistent selector definition style

The new selectors use arrow functions while existing selectors use direct string assignments. Consider maintaining consistency with the existing pattern:

-  sidebarToggle = () => cy.get('[data-testid="sidebar-toggle"]');
-  sidebarItems = () => cy.get('[data-testid="sidebar-item"]');
+  sidebarToggle = '[data-testid="sidebar-toggle"]';
+  sidebarItems = '[data-testid="sidebar-item"]';

Then update the methods to use cy.get(this.sidebarToggle) and cy.get(this.sidebarItems).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eb07939 and 5f57f05.

📒 Files selected for processing (3)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/pageobject/Facility/FacilityHome.ts (2 hunks)
  • src/components/Common/Sidebar/SidebarItem.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts
  • src/components/Common/Sidebar/SidebarItem.tsx
🔇 Additional comments (1)
cypress/pageobject/Facility/FacilityHome.ts (1)

7-8: Implementation aligns well with PR objectives

The added methods provide a solid foundation for testing sidebar collapse functionality:

  • Clear separation of concerns between interaction and verification
  • Comprehensive checks for both expanded and collapsed states
  • Use of reliable data-testid selectors

Also applies to: 111-129

Comment on lines 115 to 120
verifyIconsAndTextVisible() {
this.sidebarItems().each(($item) => {
cy.wrap($item).find('[data-testid="sidebar-icon"]').should("be.visible");
cy.wrap($item).find('[data-testid="sidebar-text"]').should("be.visible");
});
}
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 verification methods reliability and reduce duplication

Consider these improvements:

  1. Add timeout and empty check
  2. Extract common verification logic
+ private verifySidebarElements(textVisibility: 'be.visible' | 'not.be.visible') {
+   this.sidebarItems().should('have.length.at.least', 1)
+     .each(($item) => {
+       cy.wrap($item, { timeout: 10000 })
+         .find('[data-testid="sidebar-icon"]')
+         .should('be.visible');
+       cy.wrap($item, { timeout: 10000 })
+         .find('[data-testid="sidebar-text"]')
+         .should(textVisibility);
+     });
+ }

  verifyIconsAndTextVisible() {
-   this.sidebarItems().each(($item) => {
-     cy.wrap($item).find('[data-testid="sidebar-icon"]').should("be.visible");
-     cy.wrap($item).find('[data-testid="sidebar-text"]').should("be.visible");
-   });
+   this.verifySidebarElements('be.visible');
  }

  verifyIconsVisibleAndTextHidden() {
-   this.sidebarItems().each(($item) => {
-     cy.wrap($item).find('[data-testid="sidebar-icon"]').should("be.visible");
-     cy.wrap($item)
-       .find('[data-testid="sidebar-text"]')
-       .should("not.be.visible");
-   });
+   this.verifySidebarElements('not.be.visible');
  }

Also applies to: 122-129

Comment on lines 111 to 113
toggleSidebar() {
this.sidebarToggle().click();
}
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 visibility check before clicking

To prevent flaky tests, consider adding a visibility check before clicking:

  toggleSidebar() {
-    this.sidebarToggle().click();
+    this.sidebarToggle().should('be.visible').click();
  }
📝 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
toggleSidebar() {
this.sidebarToggle().click();
}
toggleSidebar() {
this.sidebarToggle().should('be.visible').click();
}

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/pageobject/Facility/FacilityHome.ts (2)

111-113: Consider adding error handling for better test stability

While the implementation correctly checks for visibility before clicking, consider adding error handling for cases where the toggle action fails.

 toggleSidebar() {
-  this.sidebarToggle().should("be.visible").click();
+  this.sidebarToggle()
+    .should("be.visible")
+    .click()
+    .should("exist")
+    .then(($el) => {
+      // Verify the click was successful
+      if (!$el) {
+        throw new Error("Sidebar toggle action failed");
+      }
+    });
 }

115-128: Consider adding retry mechanism for better test stability

While the implementation is solid, consider adding retry logic for better handling of flaky scenarios where elements might take longer to update their visibility state.

 private verifySidebarElements(
   textVisibility: "be.visible" | "not.be.visible",
 ) {
   this.sidebarItems()
     .should("have.length.at.least", 1)
-    .each(($item) => {
-      cy.wrap($item, { timeout: 10000 })
-        .find('[data-testid="sidebar-icon"]')
-        .should("be.visible");
-      cy.wrap($item, { timeout: 10000 })
-        .find('[data-testid="sidebar-text"]')
-        .should(textVisibility);
-    });
+    .each(($item) => {
+      const retryOptions = {
+        timeout: 10000,
+        interval: 500,
+      };
+      
+      cy.wrap($item)
+        .find('[data-testid="sidebar-icon"]')
+        .should("be.visible", retryOptions);
+        
+      cy.wrap($item)
+        .find('[data-testid="sidebar-text"]')
+        .should(textVisibility, retryOptions);
+    });
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5f57f05 and 3d06dba.

📒 Files selected for processing (1)
  • cypress/pageobject/Facility/FacilityHome.ts (2 hunks)
🔇 Additional comments (2)
cypress/pageobject/Facility/FacilityHome.ts (2)

7-8: LGTM! Well-structured selectors using data-testid

The selectors follow Cypress best practices by using data-testid attributes and are implemented as functions for better dynamic element selection.


130-136: LGTM! Well-structured verification methods

The public verification methods are well-named and effectively utilize the private helper method, following the DRY principle.

@Alokih Alokih requested a review from nihal467 November 12, 2024 06:33
.should("be.visible");
cy.wrap($item, { timeout: 10000 })
.find('[data-testid="sidebar-text"]')
.should(textVisibility);
Copy link
Member

@nihal467 nihal467 Nov 18, 2024

Choose a reason for hiding this comment

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

As mentioned earlier, ensure that the exact text is verified. For example, confirm that the text corresponding to the facility icon is precisely "Facilities" and not just any visible text. Similarly, verify the exact text for other icons as well.

@nihal467
Copy link
Member

@Alokih make the requested changes

@Alokih
Copy link
Contributor Author

Alokih commented Nov 18, 2024

@nihal467 I have my end sem exams going on currently. Can I do it after few days ?

@github-actions github-actions bot added needs-triage question Further information is requested labels Nov 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Refactor the Facility Export existing cypress test and Add New Sidebar collapse test along with it
3 participants