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

Cypress tests replace cy.wait with cy.intercept or dynamic waits #8963

Conversation

Rishith25
Copy link
Contributor

@Rishith25 Rishith25 commented Oct 29, 2024

Proposed Changes

Fixes #8925

  • Replaced hardcoded cy.wait() with cy.intercept() for API requests
  • Implemented dynamic waits to reduce flakiness in tests
  • Improved overall test reliability

@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.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Enhanced test coverage for patient consultations, discharges, and log updates.
    • Added new methods for intercepting and verifying API requests across various functionalities.
    • Introduced dynamic waits and visibility checks to improve test reliability.
  • Bug Fixes

    • Corrected success notification messages for inventory management.
    • Improved error handling for invalid inputs during user management.
  • Chores

    • Removed static wait commands in favor of intercepts for better performance and responsiveness.

@Rishith25 Rishith25 requested a review from a team as a code owner October 29, 2024 14:40
Copy link

netlify bot commented Oct 29, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 31282ab
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/67629ce0857bb8000872c51b
😎 Deploy Preview https://deploy-preview-8963--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.

@Jacobjeevan
Copy link
Contributor

Have you committed all the changes? 🤔 I'm not seeing any added cy.intercept calls in the changeset.

@Jacobjeevan Jacobjeevan added the question Further information is requested label Oct 30, 2024
@Rishith25
Copy link
Contributor Author

@Jacobjeevan I reviewed all the Cypress test cases, and it looks like the necessary cy.intercept() calls were already in place. I went ahead and removed the cy.wait() calls where they were unnecessary and added two dynamic waits in specific files to ensure smoother test execution. If I misunderstood anything or missed any cy.intercept() implementations, please let me know.

@Jacobjeevan Jacobjeevan added needs testing needs review and removed question Further information is requested labels Oct 30, 2024
.env Outdated Show resolved Hide resolved
Copy link
Member

@nihal467 nihal467 left a comment

Choose a reason for hiding this comment

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

  • According to the issue, you should replace cy.wait with cy.intercept() to verify that the relevant APIs are being fetched. However, in your PR, you only removed cy.wait without adding any cy.intercept to the code. Please make the necessary changes.
  • Make sure that post your changes, cypress action also passes fully

@nihal467
Copy link
Member

nihal467 commented Nov 4, 2024

@Rishith25 The cy.wait command was initially added in the test to prevent flakiness. The issue was created to replace hardcorded wait with cy.intercept, ensuring that tests dynamically wait for the necessary API to load and verify that the page is fully loaded before executing the next step in the test.

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

github-actions bot commented Nov 6, 2024

👋 Hi, @Rishith25,
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 bot commented Nov 6, 2024

Walkthrough

The pull request introduces comprehensive updates to the Cypress end-to-end test suite across multiple files. The primary focus is on replacing hardcoded cy.wait() commands with more robust cy.intercept() methods for API request handling. Changes span various domains including facility inventory, patient consultations, user management, and asset tracking. The modifications aim to improve test reliability, reduce flakiness, and enhance the overall test suite's responsiveness by implementing dynamic waiting mechanisms and precise API response verifications.

Changes

File Path Change Summary
cypress/e2e/facility_spec/FacilityInventory.cy.ts Added network request interceptions, updated success notification messages, corrected method names
cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts Enhanced test cases with new API intercepts, improved error handling and diagnosis selection
cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts Added discharge patient interception, improved verification steps, removed static waits
cypress/pageobject/* Multiple files updated with new intercept methods, removed static wait commands, added dynamic verification

Assessment against linked issues

Objective Addressed Explanation
Replace hardcoded cy.wait() Systematic replacement of static waits with cy.intercept() across multiple test files
Reduce test flakiness Dynamic waiting and API response verification implemented

Possibly related issues

Possibly related PRs

Suggested labels

tested, cypress, test-improvement

Suggested reviewers

  • rithviknishad
  • nihal467

Poem

🐰 Hop, hop, through the code we go,
Replacing waits with intercepts so slow,
No more static delays, our tests now fly,
Cypress magic makes our test suite sigh!
Reliability leaps, flakiness dies,
A rabbit's testing paradise! 🚀


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 266e1c5 and a984390.

📒 Files selected for processing (3)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts (2 hunks)
  • cypress/pageobject/Patient/PatientCreation.ts (4 hunks)
💤 Files with no reviewable changes (1)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts
  • cypress/pageobject/Patient/PatientCreation.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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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 (7)
cypress/pageobject/Patient/PatientPrescription.ts (1)

64-64: LGTM! Consider using verifyAndClickElement for consistency.

The change from hardcoded wait to visibility check is a good improvement that aligns with Cypress best practices and reduces test flakiness. For consistency with other methods in this class (e.g., clickAddPrescription), consider using the helper method verifyAndClickElement.

-    cy.get("#discontinuedReason").should("be.visible").type(reason);
+    cy.verifyAndClickElement("#discontinuedReason", reason);
cypress/pageobject/Patient/PatientFileupload.ts (1)

23-24: Great improvement using dynamic waits!

The replacement of hardcoded waits with dynamic element state checks is a solid improvement that aligns with Cypress best practices. This change will make the tests more reliable by ensuring actions are only performed when elements are actually ready.

Consider adding custom timeout and error messages for better debugging:

-    cy.get("#stop-recording").should("be.enabled").click();
-    cy.get("#save-recording").should("be.enabled").click();
+    cy.get("#stop-recording", { timeout: 10000 })
+      .should("be.enabled", { message: "Stop recording button should be enabled" })
+      .click();
+    cy.get("#save-recording", { timeout: 10000 })
+      .should("be.enabled", { message: "Save recording button should be enabled" })
+      .click();
cypress/e2e/facility_spec/FacilityCreation.cy.ts (5)

35-35: Consider using dynamic date generation instead of hardcoded date.

Replace the hardcoded date with a dynamic date generation to prevent future maintenance issues and make tests more robust.

-  const triageDate = "03122023";
+  const triageDate = Cypress.dayjs().format('DDMMYYYY');

Line range hint 82-127: Add API interceptions for facility triage operations.

The test performs multiple API operations without intercepting the requests. To improve reliability and align with the PR objectives of replacing hardcoded waits, consider adding cy.intercept() for the following operations:

  • Facility search API
  • Triage form submission
  • Triage data retrieval
  • Triage edit operations

Example implementation:

// Before the test
cy.intercept('GET', '/api/v1/facility/search*').as('facilitySearch');
cy.intercept('POST', '/api/v1/facility/*/triage').as('createTriage');
cy.intercept('GET', '/api/v1/facility/*/triage').as('getTriage');
cy.intercept('PUT', '/api/v1/facility/*/triage/*').as('updateTriage');

// After operations
manageUserPage.typeFacilitySearch(facilityName2);
cy.wait('@facilitySearch');

// After form submission
manageUserPage.clickSubmit();
cy.wait('@createTriage');

// Before verifying table data
cy.wait('@getTriage');
facilityPage.verifyTriageTableContains(initialTriageValue);

Line range hint 129-223: Improve test reliability with API interceptions and dynamic notification handling.

The test performs facility creation with multiple API calls but lacks proper request interception. Also, cy.closeNotification() might be timing-dependent.

  1. Add API interceptions:
// Before the test
cy.intercept('POST', '/api/v1/facility').as('createFacility');
cy.intercept('POST', '/api/v1/facility/*/bed').as('addBedCapacity');
cy.intercept('POST', '/api/v1/facility/*/doctor').as('addDoctorCapacity');
cy.intercept('DELETE', '/api/v1/facility/*').as('deleteFacility');

// After form submissions
facilityPage.submitForm();
cy.wait('@createFacility');

facilityPage.clickbedcapcityaddmore();
cy.wait('@addBedCapacity');
  1. Replace notification handling with a more reliable approach:
// Custom command in commands.ts
Cypress.Commands.add('waitForNotification', (message: string) => {
  cy.get('.notification-message')
    .should('be.visible')
    .and('contain', message);
  cy.get('.notification-close')
    .should('be.visible')
    .click();
});

// In test
cy.waitForNotification('Bed capacity added successfully');

Line range hint 225-266: Add API interceptions and improve URL verification.

The test lacks proper request interception and the URL verification could be flaky.

// Before the test
cy.intercept('POST', '/api/v1/facility').as('createFacility');
cy.intercept('POST', '/api/v1/facility/*/bed').as('addBedCapacity');
cy.intercept('POST', '/api/v1/facility/*/doctor').as('addDoctorCapacity');
cy.intercept('GET', '/api/v1/facility/search*').as('facilitySearch');

// After form submissions
facilityPage.submitForm();
cy.wait('@createFacility').then((interception) => {
  const facilityId = interception.response.body.id;
  // Verify URL contains the new facility ID
  cy.url().should('include', `/facility/${facilityId}`);
});

// After search
manageUserPage.typeFacilitySearch(facilityName);
cy.wait('@facilitySearch');

Line range hint 268-397: Add API interceptions for remaining facility operations.

The remaining tests perform various facility operations without proper request interception. This could lead to flaky tests.

Add these interceptions:

// Facility operations
cy.intercept('POST', '/api/v1/facility').as('createFacility');
cy.intercept('PUT', '/api/v1/facility/*').as('updateFacility');
cy.intercept('PUT', '/api/v1/facility/*/middleware').as('updateMiddleware');

// After facility update
facilityPage.submitForm();
cy.wait('@updateFacility');

// After middleware update
facilityPage.clickupdateMiddleWare();
cy.wait('@updateMiddleware');

Consider creating a custom command for common facility operations to reduce code duplication:

// commands.ts
Cypress.Commands.add('setupFacilityInterceptions', () => {
  cy.intercept('POST', '/api/v1/facility').as('createFacility');
  cy.intercept('PUT', '/api/v1/facility/*').as('updateFacility');
  cy.intercept('DELETE', '/api/v1/facility/*').as('deleteFacility');
  // ... other common interceptions
});

// In beforeEach
beforeEach(() => {
  cy.viewport(1280, 720);
  cy.restoreLocalStorage();
  cy.setupFacilityInterceptions();
  cy.awaitUrl("/facility");
});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0925884 and f5d5cc8.

📒 Files selected for processing (20)
  • .env (1 hunks)
  • cypress/e2e/assets_spec/AssetHomepage.cy.ts (0 hunks)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (1 hunks)
  • cypress/e2e/facility_spec/FacilityInventory.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientPrescription.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts (0 hunks)
  • cypress/e2e/users_spec/UsersCreation.cy.ts (0 hunks)
  • cypress/e2e/users_spec/UsersManage.cy.ts (0 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (0 hunks)
  • cypress/pageobject/Patient/PatientConsultation.ts (0 hunks)
  • cypress/pageobject/Patient/PatientCreation.ts (0 hunks)
  • cypress/pageobject/Patient/PatientDoctorNotes.ts (0 hunks)
  • cypress/pageobject/Patient/PatientFileupload.ts (1 hunks)
  • cypress/pageobject/Patient/PatientLogupdate.ts (0 hunks)
  • cypress/pageobject/Patient/PatientPrescription.ts (1 hunks)
  • cypress/pageobject/Patient/PatientTransfer.ts (0 hunks)
  • cypress/pageobject/Users/ManageUserPage.ts (1 hunks)
💤 Files with no reviewable changes (14)
  • cypress/e2e/assets_spec/AssetHomepage.cy.ts
  • cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts
  • cypress/e2e/patient_spec/PatientPrescription.cy.ts
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts
  • cypress/e2e/users_spec/UsersCreation.cy.ts
  • cypress/e2e/users_spec/UsersManage.cy.ts
  • cypress/pageobject/Facility/FacilityCreation.ts
  • cypress/pageobject/Patient/PatientConsultation.ts
  • cypress/pageobject/Patient/PatientCreation.ts
  • cypress/pageobject/Patient/PatientDoctorNotes.ts
  • cypress/pageobject/Patient/PatientLogupdate.ts
  • cypress/pageobject/Patient/PatientTransfer.ts
✅ Files skipped from review due to trivial changes (1)
  • .env
🔇 Additional comments (4)
cypress/pageobject/Patient/PatientFileupload.ts (1)

Line range hint 1-116: Excellent use of cy.intercept throughout the file!

The file demonstrates proper handling of API requests using cy.intercept and appropriate status code assertions. This is exactly the pattern we want to maintain for reliable tests.

cypress/e2e/facility_spec/FacilityInventory.cy.ts (1)

36-38: ⚠️ Potential issue

Add cy.intercept for API calls to prevent test flakiness.

While the success message update is appropriate, the test is missing proper API request handling. Each inventory operation (create, modify, delete) should wait for its corresponding API response.

Example implementation:

// Before the test
cy.intercept('POST', '**/api/inventory/use_stock').as('updateStock')
cy.intercept('POST', '**/api/inventory/create').as('createInventory')

// In the test
facilityPage.clickAddInventory();
cy.wait('@createInventory')
facilityPage.verifySuccessNotification("Inventory created successfully");

facilityPage.clickAddInventory();
cy.wait('@updateStock')
facilityPage.verifySuccessNotification("Inventory use stock updated successfully");
cypress/pageobject/Users/ManageUserPage.ts (2)

44-44: Good improvement in click reliability!

The addition of .should("be.visible") check before clicking is a good practice. It replaces the forced click with a dynamic wait that ensures the element is actually interactable, making the test more reliable.


Line range hint 1-190: Consider standardizing API interception patterns across methods

Some methods like navigateToProfile and clickAddSkillButton properly use cy.intercept to wait for API responses, while others don't. Consider standardizing this pattern across all methods that trigger API calls to ensure consistent test reliability.

For example, methods like clickLinkFacility, clickUnlinkFacilityButton, and clickUnlinkSkill likely trigger API calls and could benefit from similar interception patterns.

Let's verify which methods might need API interceptions:

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

github-actions bot commented Nov 9, 2024

👋 Hi, @Rishith25,
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.

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

@Rishith25 what is the status on this PR

1 similar comment
@nihal467
Copy link
Member

@Rishith25 what is the status on this PR

@Rishith25
Copy link
Contributor Author

@nihal467 Can you please help me to get it solved.

https://github.com/ohcnetwork/care_fe/actions/runs/12354446070/job/34475813772?pr=8963

I did not change anything in the FacilityCreation.cy.ts.
The test cases are always failing even after making required changes.

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 16, 2024
@nihal467 nihal467 self-assigned this Dec 16, 2024
@nihal467 nihal467 removed question Further information is requested needs-triage labels Dec 16, 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: 3

🧹 Nitpick comments (10)
src/components/ui/tooltip.tsx (1)

14-17: Add displayName for better debugging

Add a displayName to the forwardRef component for better debugging experience.

 const TooltipComponent = React.forwardRef<
   React.ElementRef<typeof TooltipContent>,
   React.ComponentPropsWithoutRef<typeof TooltipPrimitive.Content>
 >(({ children, content, sideOffset = 4, className }, ref) => {
+
+TooltipComponent.displayName = 'TooltipComponent';
src/components/Common/Sidebar/Sidebar.tsx (1)

241-253: Optimize tooltip content and improve button accessibility

Consider these improvements for better performance and accessibility:

+const getTooltipContent = (shrinked: boolean, t: TFunction) => 
+  shrinked ? t("expand_sidebar") : t("collapse_sidebar");

 const ToggleShrink = ({ shrinked, toggle }: ToggleShrinkProps) => {
   const { t } = useTranslation();
+  const tooltipContent = useMemo(() => getTooltipContent(shrinked, t), [shrinked, t]);
   return (
     <TooltipProvider>
       <TooltipComponent
-        content={shrinked ? t("expand_sidebar") : t("collapse_sidebar")}
+        content={tooltipContent}
       >
         <button
+          aria-label={tooltipContent}
           className={`flex h-6 w-6 cursor-pointer items-center justify-center rounded focus:outline-none focus:ring-2 focus:ring-indigo-500 ${
src/components/Facility/FacilityCard.tsx (1)

103-124: Improve occupancy badge implementation

The occupancy badge implementation could be improved for better maintainability and accessibility.

+const HIGH_OCCUPANCY_THRESHOLD = 0.85;
+
+const getOccupancyRatio = (patientCount: number, bedCount: number) => 
+  (patientCount || 0) / (bedCount || 0);
+
+const getOccupancyBadgeClass = (ratio: number) =>
+  ratio > HIGH_OCCUPANCY_THRESHOLD
+    ? "justify-center rounded-md border border-red-600 bg-red-500 p-1 font-bold text-white"
+    : "text-secondary-700";

 <TooltipProvider>
   <TooltipComponent
-    content={t("live_patients_total_beds")}
+    content={t("occupancy_tooltip", {
+      patients: facility.patient_count,
+      beds: facility.bed_count,
+      ratio: ((facility.patient_count || 0) / (facility.bed_count || 0) * 100).toFixed(1)
+    })}
   >
     <div
       data-test-id="occupancy-badge"
+      aria-label={`Occupancy: ${facility.patient_count} out of ${facility.bed_count} beds`}
       className={`relative flex items-center gap-1 text-sm ${
-        (facility.patient_count || 0) / (facility.bed_count || 0) > 0.85
-          ? "justify-center rounded-md border border-red-600 bg-red-500 p-1 font-bold text-white"
-          : "text-secondary-700"
+        getOccupancyBadgeClass(getOccupancyRatio(facility.patient_count, facility.bed_count))
       }`}
     >
src/components/Facility/DischargedPatientsList.tsx (3)

70-103: Consider adding a TypeScript interface for search options

While the search options are well-structured, adding a TypeScript interface would improve type safety and maintainability.

interface SearchOption {
  key: string;
  label: string;
  type: 'text' | 'phone';
  placeholder: string;
  value: string;
  shortcutKey: string;
}

const searchOptions: SearchOption[] = [
  // ... existing options
];

268-268: Consider setting initial loading state to true

The loading state implementation is good, but to prevent a flash of empty content, consider initializing isLoading to true.

- const [isLoading, setIsLoading] = useState(false);
+ const [isLoading, setIsLoading] = useState(true);

Also applies to: 300-307, 428-431


309-315: Consider debouncing search operations

For better performance and to reduce unnecessary API calls, consider implementing debounce on the search operations, especially for text-based searches.

import { debounce } from 'lodash';

const debouncedHandleSearch = useCallback(
  debounce((key: string, value: string) => {
    handleSearch(key, value);
  }, 300),
  [handleSearch]
);
src/components/Form/FormFields/AutocompleteMultiselect.tsx (1)

176-178: Consider using a more maintainable approach for conditional positioning

The current implementation has potential issues:

  1. The hardcoded -top-5 value could cause maintenance issues if the component's height changes
  2. The string interpolation makes it harder to maintain type safety with CSS classes

Consider using Tailwind's built-in conditional class utilities:

-<div
-  className={`relative flex items-center justify-center text-lg text-secondary-900 ${value.some((val: any) => val.option) ? "-top-5" : ""}`}
->
+<div
+  className={classNames(
+    "relative flex items-center justify-center text-lg text-secondary-900",
+    value.some((val) => val.option) && "-translate-y-5"
+  )}
+>

This approach:

  • Uses CSS transform instead of top positioning for better performance
  • Leverages the existing classNames utility for better type safety
  • Removes the any type assertion
src/components/Common/DateInputV2.tsx (2)

394-394: Ensure 'placeholder' is defined before setting 'title' attribute

The title attribute is set to placeholder, but if placeholder is undefined or an empty string, the title will also be empty, which might not be useful.

Consider updating the code to only set the title attribute when placeholder is defined:

<input
  id={id}
  name={name}
  type="text"
  readOnly
  disabled={disabled}
  data-scribe-ignore
  className={`cui-input-base cursor-pointer disabled:cursor-not-allowed ${className}`}
  placeholder={placeholder ?? t("select_date")}
- title={placeholder}
+ title={placeholder || undefined}
  value={value ? dayjs(value).format(dateFormat) : ""}
/>

652-657: Simplify nested ternary operators for readability

The nested ternary operators in the className prop can reduce code readability and maintainability.

Consider refactoring using a helper function for clarity:

+ const getMonthClassName = (month: number) => {
+   if (isSelectedMonth(month)) {
+     return "bg-primary-500 text-white cursor-pointer";
+   } else if (isMonthWithinConstraints(month)) {
+     return "text-secondary-700 hover:bg-secondary-300 cursor-pointer";
+   } else {
+     return "!text-secondary-400 !cursor-not-allowed";
+   }
+ };

<div
  key={i}
  id={`month-${i}`}
- className={classNames(
-   "w-1/4 rounded-lg px-2 py-4 text-center text-sm font-semibold",
-   isSelectedMonth(i)
-     ? "bg-primary-500 text-white cursor-pointer"
-     : isMonthWithinConstraints(i)
-       ? "text-secondary-700 hover:bg-secondary-300 cursor-pointer"
-       : "!text-secondary-400 !cursor-not-allowed",
- )}
+ className={classNames(
+   "w-1/4 rounded-lg px-2 py-4 text-center text-sm font-semibold",
+   getMonthClassName(i),
+ )}
  onClick={setMonthValue(i)}
>
src/components/Form/FormFields/DateFormField.tsx (1)

40-43: Confirm necessity of 'mr-9' and 'text-ellipsis' classes in 'className'

The addition of mr-9 (right margin) and text-ellipsis (text truncation) classes to the className prop may affect the layout and display of the date input field.

Please ensure that these styles are intentional and do not negatively impact the component's appearance or user experience.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 86492c3 and 5be34d7.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (9)
  • package.json (1 hunks)
  • src/components/Common/DateInputV2.tsx (8 hunks)
  • src/components/Common/Sidebar/Sidebar.tsx (2 hunks)
  • src/components/Facility/DischargedPatientsList.tsx (6 hunks)
  • src/components/Facility/FacilityCard.tsx (2 hunks)
  • src/components/Form/FormFields/AutocompleteMultiselect.tsx (1 hunks)
  • src/components/Form/FormFields/DateFormField.tsx (1 hunks)
  • src/components/Form/ModelCrudEditor.tsx (1 hunks)
  • src/components/ui/tooltip.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Form/ModelCrudEditor.tsx
🔇 Additional comments (8)
package.json (2)

70-70: Verify @sentry/browser version compatibility

The version bump from ^8.42.0 to ^8.45.1 should be verified for:

  1. Breaking changes
  2. Compatibility with other dependencies
✅ Verification successful

Based on the changelog information provided, I can now generate the final response:

@sentry/browser version upgrade appears safe

The version upgrade from 8.42.0 to 8.45.1 includes:

  • No breaking changes in this version range
  • Only feature additions and bug fixes
  • No compatibility issues with other dependencies as this is the only Sentry package in use

The main changes are bug fixes and improvements:

  • Enhanced console capture integration
  • Improved stack trace handling
  • Better HTTP client event tracking
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for breaking changes in the version range
curl -s https://raw.githubusercontent.com/getsentry/sentry-javascript/master/CHANGELOG.md | grep -A 10 "8.4"

# Check if this version is used in other related packages
rg '"@sentry/.*":\s*"\^8' 

Length of output: 9244


70-70: Verify relevance of @sentry/browser update to PR objectives

This change appears unrelated to the PR's main objective of replacing cy.wait with cy.intercept. Consider:

  1. Moving this dependency update to a separate PR
  2. Documenting why this update is necessary in this PR
src/components/Facility/DischargedPatientsList.tsx (2)

2-2: LGTM: Import statements are properly updated

The new imports for useCallback and SearchByMultipleFields are correctly added to support the enhanced search functionality.

Also applies to: 14-14


53-68: LGTM: Proper configuration of useFilters hook

Good addition of clearSearch and appropriate cacheBlacklist configuration for search-related fields. This prevents unwanted caching of search parameters.

src/components/Form/FormFields/AutocompleteMultiselect.tsx (3)

174-174: LGTM: Improved button content alignment

The addition of justify-center ensures proper horizontal centering of the button content, which is consistent with standard button layout practices.


185-185: LGTM: Improved icon sizing approach

The change from manual margin adjustment (-mb-1.5) to using the text size utility (text-lg) is a better approach as it:

  • Follows the design system's sizing conventions
  • Is more maintainable and consistent with other icon implementations

174-185: Verify the scope of UI changes in this PR

While these UI improvements are valid, they seem unrelated to the PR's main objective of replacing cy.wait with cy.intercept in Cypress tests. Please clarify if these UI changes should be in a separate PR to maintain focused scope.

src/components/Common/DateInputV2.tsx (1)

114-120: ⚠️ Potential issue

Incorrect increment logic for 'month' type

Similarly, in the increment function, when the type is "month", it incorrectly adds one year instead of one month. This will cause the date picker to jump forward a year instead of a month when the user tries to increment the month.

Apply this diff to fix the issue:

case "month":
  setDatePickerHeaderDate((prev) => {
-    const newDate = dayjs(prev).add(1, "year").toDate();
+    const newDate = dayjs(prev).add(1, "month").toDate();
    if (max && newDate > max) {
      return new Date(max.getFullYear(), max.getMonth(), 1);
    }
    return newDate;
  });

Likely invalid or redundant comment.

src/components/ui/tooltip.tsx Outdated Show resolved Hide resolved
src/components/Facility/DischargedPatientsList.tsx Outdated Show resolved Hide resolved
src/components/Common/DateInputV2.tsx Outdated Show resolved Hide resolved
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 comments (1)
cypress/pageobject/Facility/FacilityCreation.ts (1)

Line range hint 86-89: Replace hardcoded timeouts with dynamic waits

Using hardcoded timeouts (20000ms, 10000ms) can make tests flaky. Instead, use Cypress's retry-ability with shorter default timeouts.

  clickManageFacilityDropdown() {
-   cy.get("h1.text-3xl.font-bold", { timeout: 20000 }).should("be.visible");
+   cy.get("h1.text-3xl.font-bold").should("be.visible");
    cy.get("#manage-facility-dropdown button").scrollIntoView();
    cy.get("#manage-facility-dropdown button")
      .contains("Manage Facility")
      .click();
  }

  clickInventoryManagementOption() {
-   cy.get("#inventory-management", { timeout: 10000 }).should("be.visible");
+   cy.get("#inventory-management").should("be.visible");
    cy.get("#inventory-management").click();
  }

Also applies to: 95-97

♻️ Duplicate comments (1)
cypress/pageobject/Facility/FacilityCreation.ts (1)

65-71: ⚠️ Potential issue

Fix incorrect status code expectation

The verifyErrorFacility method expects a 403 status code, but error responses could also be 401 for unauthorized access.

Apply this fix to handle both error cases:

  verifyErrorFacility() {
-   cy.wait("@postFacility").its("response.statusCode").should("eq", 403);
+   cy.wait("@postFacility").then(interception => {
+     expect(interception.response.statusCode).to.be.oneOf([401, 403]);
+   });
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c4ace63 and 266e1c5.

📒 Files selected for processing (3)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (0 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (7 hunks)
  • cypress/pageobject/utils/advanceFilterHelpers.ts (1 hunks)
💤 Files with no reviewable changes (1)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts
🧰 Additional context used
📓 Learnings (1)
cypress/pageobject/Facility/FacilityCreation.ts (2)
Learnt from: nihal467
PR: ohcnetwork/care_fe#9436
File: cypress/pageobject/Facility/FacilityHome.ts:12-12
Timestamp: 2024-12-15T17:02:16.697Z
Learning: In this codebase, `cy.awaitUrl()` is a custom Cypress command that includes `cy.visit()` and performs navigation.
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9145
File: cypress/e2e/facility_spec/FacilityCreation.cy.ts:177-180
Timestamp: 2024-11-18T10:44:30.303Z
Learning: In `cypress/e2e/facility_spec/FacilityCreation.cy.ts`, when testing bed and staff capacity individually for additional error verification, we prefer to use separate method calls to handle bed and staff capacity, rather than using `facilityPage.createNewFacility(testFacilityData)` which also handles bed management.
🔇 Additional comments (4)
cypress/pageobject/Facility/FacilityCreation.ts (4)

226-227: Avoid using generic IDs like id in selectors

Using div#id as a selector might lead to unintended behavior if multiple elements share this generic ID. Consider using a more specific and unique ID.


211-221: Good use of cy.intercept for inventory items

The addition of intercept and verification methods for inventory items aligns well with the PR's objective of replacing static waits with proper request interception.


305-317: Good use of cy.intercept for minimum quantity

The addition of intercept and verification methods for minimum quantity aligns well with the PR's objective of replacing static waits with proper request interception.


169-169: Good use of visibility check

The addition of visibility check before clicking the close button is a good practice that aligns with the PR's objective of using dynamic waits.

@rithviknishad rithviknishad merged commit 3979b53 into ohcnetwork:develop Dec 18, 2024
22 checks passed
Copy link

@nihal467 @Rishith25 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! 🙌

@Rishith25
Copy link
Contributor Author

Thank you @nihal467 for helping me out.

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.

Replace Hardcoded cy.wait() with cy.intercept in the cypress files
6 participants