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

New Cypress Test for HCX Workflow in the platform #9007

Merged
merged 10 commits into from
Nov 12, 2024
Merged

Conversation

nihal467
Copy link
Member

@nihal467 nihal467 commented Nov 5, 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 an end-to-end test suite for HCX Claims configuration and approval workflow.
    • Added tests for patient filtering options and export functionalities on the Patient Homepage.
    • Enhanced patient registration tests to streamline insurance entry processes.
    • Updated the Patient Consultation page with new interaction methods.
    • Added a button for updating patient details in the Patient Home component.
  • Bug Fixes

    • Improved notification handling for patient transfers and sample test requests.
    • Corrected a typographical error in the ConsultationCard button ID.
  • Documentation

    • Enhanced accessibility features in the HCX Policy Eligibility Check component.
  • Tests

    • Expanded test coverage for various patient-related functionalities across multiple components.
    • Improved Cypress workflow configuration for enhanced testing conditions.

Copy link

coderabbitai bot commented Nov 5, 2024

Walkthrough

The changes introduce a comprehensive set of end-to-end tests for the HCX Claims configuration and patient management workflows using Cypress. New test cases are added for verifying patient filtering, insurance handling, and consultation interactions. Additionally, several classes are updated with new methods to enhance functionality related to patient details and insurance policy management. The Cypress workflow configuration is also modified to accommodate new environment variables and job conditions for testing in different scenarios.

Changes

File Path Change Summary
cypress/e2e/hcx_spec/HcxClaims.cy.ts Introduced a new end-to-end test suite for HCX Claims workflow, including login and eligibility checks.
cypress/e2e/patient_spec/PatientHomepage.cy.ts Added new test case for patient filtering and updated export notification and pagination tests.
cypress/e2e/patient_spec/PatientRegistration.cy.ts Simplified insurance entry logic by removing conditional checks and updating insurer names.
cypress/pageobject/Hcx/HcxClaims.ts Added HcxClaims class with methods for selecting policies and verifying eligibility.
cypress/pageobject/Patient/PatientConsultation.ts Updated PatientConsultationPage class with new methods for managing consultations and claims.
cypress/pageobject/Patient/PatientCreation.ts Added method for updating patient details and modified request interception logic.
cypress/pageobject/Patient/PatientInsurance.ts Replaced insurer selection method and simplified policy details verification.
src/components/HCX/PolicyEligibilityCheck.tsx Added IDs for accessibility in SelectFormField and ButtonV2, with updated eligibility check logic.
src/components/Patient/PatientHome.tsx Introduced new button for patient updates and modified transfer handling functions.
.github/workflows/cypress.yaml Updated Cypress workflow with new environment variables and job conditions for testing.

Possibly related PRs

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • khavinshankar

Poem

🐰 In the meadow where the tests do play,
New workflows hop and dance all day.
Claims and patients, all in a line,
With Cypress magic, everything's fine!
So let’s cheer for the code that brings delight,
For every bug squashed, we’ll celebrate tonight! 🎉

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/hcx_spec/HcxClaims.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 5, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit fc4f060
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/673214aad0f90200080306fa
😎 Deploy Preview https://deploy-preview-9007--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

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

Deploying care-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: fc4f060
Status: ✅  Deploy successful!
Preview URL: https://061a9249.care-fe.pages.dev
Branch Preview URL: https://hcx-develop.care-fe.pages.dev

View logs

Copy link

cypress bot commented Nov 5, 2024

CARE    Run #3873

Run Properties:  status check passed Passed #3873  •  git commit fc4f060149: New Cypress Test for HCX Workflow in the platform
Project CARE
Branch Review hcx-develop
Run status status check passed Passed #3873
Run duration 04m 47s
Commit git commit fc4f060149: New Cypress Test for HCX Workflow in the platform
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 128
View all changes introduced in this branch ↗︎

Copy link

github-actions bot commented Nov 6, 2024

👋 Hi, @nihal467,
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 6, 2024
@github-actions github-actions bot added Deploy-Failed Deplyment is not showing preview and removed merge conflict pull requests with merge conflict labels Nov 10, 2024
@nihal467 nihal467 removed the Deploy-Failed Deplyment is not showing preview label Nov 10, 2024
@nihal467
Copy link
Member Author

@khavinshankan should we keep the hcx in env or is it ok to enable them in staging

@nihal467 nihal467 added the question Further information is requested label Nov 10, 2024
@nihal467 nihal467 marked this pull request as ready for review November 11, 2024 05:35
@nihal467 nihal467 requested a review from a team as a code owner November 11, 2024 05:35
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (12)
cypress/pageobject/Hcx/HcxClaims.ts (1)

1-1: Add JSDoc documentation and interface definition.

Consider adding class-level documentation and defining an interface for better maintainability and type safety:

+interface IHcxClaims {
+  selectEligiblePolicy(policy: string): void;
+  verifyPolicyEligibity(): void;
+}
+
+/**
+ * Page object class for HCX Claims functionality
+ * Handles insurance policy selection and eligibility verification
+ */
 export class HcxClaims {
cypress/pageobject/Patient/PatientConsultation.ts (1)

Inconsistent wait handling and missing documentation needs attention

The verification confirms the review's concerns:

  1. Inconsistent wait handling:

    • Only 3 wait statements in the entire class
    • selectConsultationStatus: 5000ms wait
    • clickEditConsultationButton: 3000ms wait
    • clickClaimsButton: API response wait
    • Other similar async operations (clicks, types, selects) have no waits
  2. TypeScript types are actually present for method parameters, contrary to the review's concern

  3. No JSDoc documentation exists for the class or its methods

Recommendation:

  • Standardize wait handling by using consistent wait strategies for similar operations
  • Add comprehensive JSDoc documentation
  • Consider extracting wait times into class-level constants
🔗 Analysis chain

Line range hint 1-132: Consider class-level improvements for maintainability.

The class could benefit from several improvements:

  1. Add TypeScript types for method parameters
  2. Add JSDoc documentation for methods
  3. Standardize wait handling across methods

Example improvements:

/**
 * Page object representing the Patient Consultation page.
 * Provides methods to interact with consultation-related elements.
 */
export class PatientConsultationPage {
  /**
   * Clicks the Claims button and waits for the policy status API response.
   * @throws {Error} If the API request fails or times out
   */
  clickClaimsButton(): void {
    // ... existing implementation
  }

  /**
   * Selects the consultation status from the dropdown.
   * @param status - The status to select
   */
  selectConsultationStatus(status: string): void {
    // ... existing implementation
  }
}

Also, consider extracting common wait times into class constants and standardizing their usage across methods.

Let's check for inconsistent wait handling:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Find all cy.wait occurrences and their timing values
rg "cy\.wait\(" cypress/pageobject/Patient/PatientConsultation.ts

Length of output: 180


Script:

#!/bin/bash
# Let's check for any existing type definitions and JSDoc comments
rg "\/\*\*" -A 3 cypress/pageobject/Patient/PatientConsultation.ts

# Also check if there are any other methods with potential async operations
rg "intercept|click|type|select" cypress/pageobject/Patient/PatientConsultation.ts

Length of output: 2758

cypress/e2e/hcx_spec/HcxClaims.cy.ts (5)

8-19: Consider improving test data management and type safety.

While the setup is functional, consider these improvements:

  1. Move test data to a separate fixture file for better maintainability
  2. Add type annotations for constants
  3. Use enums or constants for identifiers like "insurance-details-0"

Example implementation:

// testData/hcx.fixture.ts
export interface HcxTestData {
  patientName: string;
  insuranceIdentifier: string;
  memberId: string;
  policyId: string;
  insurerName: string;
}

export const HCX_TEST_DATA: HcxTestData = {
  patientName: "Dummy Patient 14",
  insuranceIdentifier: "insurance-details-0",
  memberId: "001",
  policyId: "100",
  insurerName: "Demo Payor"
};

20-29: Consider enhancing URL verification.

The URL verification could be more robust by:

  1. Adding a timeout
  2. Including an assertion for the exact URL pattern
-    cy.awaitUrl("/patients");
+    cy.url({ timeout: 10000 }).should('include', '/patients');
+    cy.location('pathname').should('match', /^\/patients$/);

Also applies to: 94-96


66-79: Enhance mock response structure and typing.

The mock response could benefit from proper typing and more realistic test data.

interface EligibilityResponse {
  api_call_id: string;
  correlation_id: string;
  timestamp: number;
  consultation: string;
  policy: string;
  outcome: 'Complete' | 'Pending' | 'Failed';
  limit: number;
}

const mockResponse: EligibilityResponse = {
  api_call_id: "bfa228f0-cdfa-4426-bebe-26e996079dbb",
  correlation_id: "86ae030c-1b33-4e52-a6f1-7a74a48111eb",
  timestamp: Date.now(),
  consultation: consultationId,
  policy: patientPolicyId,
  outcome: "Complete",
  limit: 1,
};

cy.intercept("POST", "/api/hcx/check_eligibility", (req) => {
  req.reply({
    statusCode: 200,
    body: mockResponse
  });
}).as("checkEligibility");
🧰 Tools
🪛 Gitleaks

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


31-92: Consider breaking down the test for better maintainability.

The test case covers multiple steps and could be split into smaller, focused test cases or use custom commands for common operations.

Example structure:

describe('HCX Claims workflow', () => {
  it('should update patient insurance details', () => {
    // Insurance update steps
  });

  it('should verify policy eligibility', () => {
    // Eligibility check steps
  });

  // More focused test cases
});

Also consider creating custom commands for common operations:

// commands.ts
Cypress.Commands.add('updatePatientInsurance', (details) => {
  // Insurance update steps
});
🧰 Tools
🪛 Gitleaks

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


88-91: Add more comprehensive assertions.

The eligibility check verification could be more thorough.

     cy.wait("@checkEligibility").then((interception) => {
       const response = interception.response.body;
-      expect(response.outcome).to.equal("Complete");
+      expect(response).to.have.property('consultation').equal(consultationId);
+      expect(response).to.have.property('policy').equal(patientPolicyId);
+      expect(response).to.have.property('outcome').equal("Complete");
+      expect(response.timestamp).to.be.a('number');
     });
src/components/HCX/PolicyEligibilityCheck.tsx (1)

Line range hint 74-143: Consider enhancing error handling for eligibility check.

While the component handles successful eligibility checks well, it could benefit from explicit error handling in the checkEligibility function. Consider showing an error notification when the API call fails.

Here's a suggested improvement:

  const checkEligibility = async () => {
    if (!selectedPolicy || isPolicyEligible()) return;

    setIsCheckingEligibility(true);

-   const { res } = await request(routes.hcx.policies.checkEligibility, {
-     body: { policy: selectedPolicy.id },
-   });
-
-   if (res?.ok) {
-     Notification.Success({ msg: t("checking_policy_eligibility") });
-   }
+   try {
+     const { res } = await request(routes.hcx.policies.checkEligibility, {
+       body: { policy: selectedPolicy.id },
+     });
+
+     if (res?.ok) {
+       Notification.Success({ msg: t("checking_policy_eligibility") });
+     } else {
+       Notification.Error({ msg: t("error_checking_eligibility") });
+     }
+   } catch (error) {
+     Notification.Error({ msg: t("error_checking_eligibility") });
+   }

    setIsCheckingEligibility(false);
  };
cypress/pageobject/Patient/PatientCreation.ts (2)

223-225: LGTM! Consider adding error handling.

The new method follows good POM practices and clearly encapsulates the update details functionality.

Consider adding error handling for cases where the element might not be present:

 clickPatientUpdateDetails() {
-  cy.verifyAndClickElement("#update-patient-details", "Update Details");
+  cy.verifyAndClickElement("#update-patient-details", "Update Details")
+    .should('exist')
+    .then($el => {
+      if (!$el) {
+        throw new Error('Update Details button not found');
+      }
+    });
 }

Line range hint 1-236: Consider enhancing the Page Object Model implementation.

The class demonstrates good POM practices, but could be further improved for maintainability and reusability:

  1. Consider extracting selectors to a separate constants file:
// selectors.ts
export const PATIENT_SELECTORS = {
  UPDATE_DETAILS: '#update-patient-details',
  PHONE_NUMBER: '#phone_number',
  // ... other selectors
};
  1. Consider grouping related methods into separate classes/modules:
  • PatientCreationPage
  • PatientUpdatePage
  • PatientVerificationPage
  1. Consider adding JSDoc comments for better documentation and type hints.

These improvements would:

  • Make selectors more maintainable
  • Improve code organization
  • Enhance code documentation
  • Make the test suite more scalable
cypress/e2e/patient_spec/PatientRegistration.cy.ts (1)

178-181: LGTM! Consider extracting insurance setup into a helper method.

The insurance selection implementation is clean and consistent. Since this pattern is repeated twice, consider extracting it into a helper method to improve test maintainability:

// Helper method in PatientInsurance class
addInsuranceDetails(insuranceId: string, subscriberId: string, policyId: string, insurerName: string) {
  this.clickAddInsruanceDetails();
  this.typePatientInsuranceDetail(insuranceId, "subscriber_id", subscriberId);
  this.typePatientInsuranceDetail(insuranceId, "policy_id", policyId);
  this.selectPatientInsurerName(insuranceId, insurerName);
}

// Usage in test
patientInsurance.addInsuranceDetails(
  patientOneFirstInsuranceId,
  patientOneFirstSubscriberId,
  patientOneFirstPolicyId,
  patientOneFirstInsurerName
);

Also applies to: 193-196

src/components/Patient/PatientHome.tsx (1)

Line range hint 681-714: LGTM! Consider these improvements for better maintainability.

The update patient details button implementation is solid with proper authorization and permission checks. However, consider these enhancements:

  1. Extract the facility permission check to a reusable function
  2. Move the error message to translation keys for i18n support

Consider this refactor:

+ const canUpdatePatientDetails = (user: any, patientFacility: string) => {
+   const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
+   return showAllFacilityUsers.includes(user.user_type) || 
+          user.home_facility_object?.id === patientFacility;
+ };

  <ButtonV2
    id="update-patient-details"
    className="mt-4 w-full"
    disabled={!patientData.is_active}
    authorizeFor={NonReadOnlyUsers}
    onClick={() => {
-     const showAllFacilityUsers = ["DistrictAdmin", "StateAdmin"];
-     if (!showAllFacilityUsers.includes(authUser.user_type) &&
-         authUser.home_facility_object?.id !== patientData.facility
-     ) {
+     if (!canUpdatePatientDetails(authUser, patientData.facility)) {
        Notification.Error({
-         msg: "Oops! Non-Home facility users don't have permission to perform this action.",
+         msg: t("error.non_home_facility_permission"),
        });
      } else {
        navigate(`/facility/${patientData?.facility}/patient/${id}/update`);
      }
    }}
  >
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 45ae794 and 8c9bbc7.

📒 Files selected for processing (10)
  • .env (1 hunks)
  • cypress/e2e/hcx_spec/HcxClaims.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (0 hunks)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts (3 hunks)
  • cypress/pageobject/Hcx/HcxClaims.ts (1 hunks)
  • cypress/pageobject/Patient/PatientConsultation.ts (2 hunks)
  • cypress/pageobject/Patient/PatientCreation.ts (1 hunks)
  • cypress/pageobject/Patient/PatientInsurance.ts (2 hunks)
  • src/components/HCX/PolicyEligibilityCheck.tsx (2 hunks)
  • src/components/Patient/PatientHome.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts
🧰 Additional context used
🪛 Gitleaks
cypress/e2e/hcx_spec/HcxClaims.cy.ts

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (6)
cypress/pageobject/Hcx/HcxClaims.ts (1)

1-9: Enhance test reliability and maintainability.

Consider the following improvements to align with Cypress best practices:

  1. Add constants for selectors and text strings
  2. Implement proper wait strategies
  3. Verify custom commands are properly typed
+ const SELECTORS = {
+   INSURANCE_POLICY: "[data-testid=insurance-policy-select]",
+   ELIGIBILITY_CHECK: "[data-testid=eligibility-check-button]"
+ } as const;
+
+ const TEXTS = {
+   CHECK_ELIGIBILITY: "Check Eligibility",
+   ELIGIBILITY_INITIATED: "Eligibility check initiated"
+ } as const;
+
 export class HcxClaims {
   selectEligiblePolicy(policy: string): void {
-    cy.clickAndSelectOption("#select-insurance-policy", policy);
+    cy.clickAndSelectOption(SELECTORS.INSURANCE_POLICY, policy, {
+      timeout: 10000
+    });
   }

-  verifyPolicyEligibity() {
-    cy.verifyAndClickElement("#check-eligibity", "Check Eligibility");
+  verifyPolicyEligibility(): void {
+    cy.verifyAndClickElement(
+      SELECTORS.ELIGIBILITY_CHECK,
+      TEXTS.CHECK_ELIGIBILITY,
+      { timeout: 10000 }
+    );
+    cy.contains(TEXTS.ELIGIBILITY_INITIATED, {
+      timeout: 10000
+    }).should("be.visible");
   }
 }

Let's verify if the custom commands are properly defined:

✅ Verification successful

Consider adding timeout options and data-testid selectors for better test stability

The custom commands clickAndSelectOption and verifyAndClickElement are properly defined and typed in the codebase. However, the implementation can be improved:

  1. Use data-testid selectors instead of id selectors:
- "#select-insurance-policy"
+ "[data-testid=insurance-policy-select]"
- "#check-eligibity"
+ "[data-testid=eligibility-check]"
  1. Add timeout options for better stability:
- cy.clickAndSelectOption("#select-insurance-policy", policy);
+ cy.clickAndSelectOption("[data-testid=insurance-policy-select]", policy, {
+   timeout: 10000
+ });
  1. Fix typo in method name:
- verifyPolicyEligibity
+ verifyPolicyEligibility
  1. Add verification for successful eligibility check:
  verifyPolicyEligibility(): void {
    cy.verifyAndClickElement(
      "[data-testid=eligibility-check]",
      "Check Eligibility",
+     { timeout: 10000 }
    );
+   cy.contains("Eligibility check initiated", {
+     timeout: 10000
+   }).should("be.visible");
  }
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if custom commands are defined in support/commands.ts
rg -t ts "Cypress.Commands.add\(('|\")(?:clickAndSelectOption|verifyAndClickElement)('|\")" cypress/support/

Length of output: 114


Script:

#!/bin/bash
# Let's try a broader search for custom commands and their types
fd "commands\.(ts|js|d\.ts)" --type f

# Also search for these specific command names anywhere in the codebase
rg -t ts "(?:clickAndSelectOption|verifyAndClickElement)"

Length of output: 5359


Script:

#!/bin/bash
# Let's check the implementation of these commands
cat cypress/support/commands.ts

# Also check the type definitions
cat cypress/support/index.ts

Length of output: 8295

cypress/pageobject/Patient/PatientInsurance.ts (2)

12-15: LGTM! Well-structured page object method.

The new selectPatientInsurerName method follows good page object pattern practices by:

  • Encapsulating the selector logic
  • Using clear parameter names
  • Maintaining single responsibility

36-36: Verify the impact of simplified verification logic.

The removal of HCX-specific checks simplifies the verification, but let's ensure this doesn't impact test coverage.

✅ Verification successful

Let me gather more context about the specific changes and their impact by checking the implementation details.


Based on the gathered information, I can now provide the final response:

Simplified verification logic is safe to proceed

The verification changes are isolated to basic UI assertions and don't impact HCX-specific test coverage:

  • The verifyPatientPolicyDetails method is only used in PatientRegistration.cy.ts for standard insurance verification
  • HCX-specific tests are separate in HcxClaims.cy.ts and don't rely on this verification logic
  • The simplified assertions still verify all required insurance details (subscriberId, policyId, insurerName)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any existing HCX-specific tests that might rely on the removed verification logic

# Search for HCX-related test files and their assertions
echo "Searching for HCX-related test files..."
rg -l "hcx" cypress/e2e
rg -l "HCX" cypress/e2e

# Search for tests using verifyPatientPolicyDetails
echo "Checking usage of verifyPatientPolicyDetails..."
rg "verifyPatientPolicyDetails" cypress/e2e -A 5

Length of output: 1246


Script:

#!/bin/bash
# Check the implementation of verifyPatientPolicyDetails and related HCX tests
echo "Checking verifyPatientPolicyDetails implementation..."
rg -A 10 "verifyPatientPolicyDetails" cypress/pageobject/Patient/PatientInsurance.ts

echo "\nChecking HCX claims test implementation..."
rg "expect.*contain" cypress/e2e/hcx_spec/HcxClaims.cy.ts

Length of output: 740

cypress/e2e/hcx_spec/HcxClaims.cy.ts (1)

1-7: LGTM! Imports are well-organized.

The imports are properly structured and all necessary page objects are imported for the test suite.

src/components/HCX/PolicyEligibilityCheck.tsx (1)

74-74: LGTM! Test automation enhancement.

The addition of the id attribute enhances the component's testability, making it easier to target in Cypress tests.

cypress/e2e/patient_spec/PatientRegistration.cy.ts (1)

60-60: LGTM! Verify these payor names match the staging environment.

The change from generic insurer names to specific payor names (Demo Payor, Care Payor) improves test readability. However, let's ensure these names match the available options in the staging environment.

Also applies to: 64-64

✅ Verification successful

Payor names are consistently used across HCX and Patient Registration tests

The verification shows that:

  • "Demo Payor" and "Care Payor" are used consistently in both HcxClaims.cy.ts and PatientRegistration.cy.ts
  • These names are used with the selectPatientInsurerName method in both test files
  • The implementation appears to be part of a coordinated update for HCX workflow testing
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for payor name references to ensure consistency
# Test: Look for these payor names in other test files and fixtures
rg -g '*.{ts,json,js}' -i "Demo Payor|Care Payor" cypress/

Length of output: 345


Script:

#!/bin/bash
# Let's check if these payor names are defined in any fixture files or configuration
rg -g '*.{json,js}' -i "payor.*data|insurers.*data|test.*data" cypress/fixtures/

Length of output: 82


Script:

#!/bin/bash
# Let's also check for any environment-specific configuration files
fd -e json -e js "environment|config" cypress/

Length of output: 70


Script:

#!/bin/bash
# Check for any mock data or setup files
rg -g '*.{ts,js}' "beforeEach|cy\.intercept.*payor|cy\.fixture.*payor" cypress/

Length of output: 2290


Script:

#!/bin/bash
# Let's check how these payor names are being used in the test files
rg -A 5 "selectPatientInsurerName|insurerName" cypress/e2e/

Length of output: 1510


Script:

#!/bin/bash
# Let's also check for any API mocks or intercepts related to insurers/payors
rg "cy\.intercept.*insurer|cy\.intercept.*payor" cypress/

Length of output: 59

Comment on lines 6 to 8
verifyPolicyEligibity() {
cy.verifyAndClickElement("#check-eligibity", "Check Eligibility");
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in method name and improve error handling.

The method has several issues that should be addressed:

  1. "Eligibity" is misspelled (should be "Eligibility")
  2. Add error handling and assertions to verify the operation succeeded
- verifyPolicyEligibity() {
+ verifyPolicyEligibility(): void {
    cy.verifyAndClickElement("#check-eligibity", "Check Eligibility");
+   cy.get("#check-eligibity").should("not.be.disabled");
+   cy.contains("Eligibility check initiated").should("be.visible");
  }
📝 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
verifyPolicyEligibity() {
cy.verifyAndClickElement("#check-eligibity", "Check Eligibility");
}
verifyPolicyEligibility(): void {
cy.verifyAndClickElement("#check-eligibity", "Check Eligibility");
cy.get("#check-eligibity").should("not.be.disabled");
cy.contains("Eligibility check initiated").should("be.visible");
}

Comment on lines +2 to +4
selectEligiblePolicy(policy: string) {
cy.clickAndSelectOption("#select-insurance-policy", policy);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve selector maintainability and add type safety.

Consider using data-testid attributes instead of CSS IDs for more reliable test selectors:

- selectEligiblePolicy(policy: string) {
+ selectEligiblePolicy(policy: string): void {
-   cy.clickAndSelectOption("#select-insurance-policy", policy);
+   cy.clickAndSelectOption("[data-testid=insurance-policy-select]", policy);
+   cy.get("[data-testid=insurance-policy-select]")
+     .should("contain.text", policy);
  }

Committable suggestion skipped: line range outside the PR's diff.

.env Outdated
@@ -14,4 +14,5 @@ ESLINT_NO_DEV_ERRORS=true
CARE_CDN_URL="https://egov-s3-facility-10bedicu.s3.amazonaws.com https://egov-s3-patient-data-10bedicu.s3.amazonaws.com http://localhost:4566"
REACT_ALLOWED_LOCALES="en,hi,ta,ml,mr,kn"

REACT_ENABLED_APPS=""
REACT_ENABLED_APPS="ohcnetwork/care_hcx_fe@main"
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using a specific version instead of @main.

Pinning to the main branch (@main) could introduce instability as the main branch can change frequently. Consider using a specific version or git tag to ensure consistent behavior across environments.

-REACT_ENABLED_APPS="ohcnetwork/care_hcx_fe@main"
+REACT_ENABLED_APPS="ohcnetwork/[email protected]"

Committable suggestion skipped: line range outside the PR's diff.

.env Outdated
@@ -14,4 +14,5 @@
CARE_CDN_URL="https://egov-s3-facility-10bedicu.s3.amazonaws.com https://egov-s3-patient-data-10bedicu.s3.amazonaws.com http://localhost:4566"
REACT_ALLOWED_LOCALES="en,hi,ta,ml,mr,kn"

REACT_ENABLED_APPS=""
REACT_ENABLED_APPS="ohcnetwork/care_hcx_fe@main"
REACT_ENABLE_HCX=true
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Environment-specific configuration for HCX should be moved to environment-specific files

The codebase has a .env.docker file and supports environment-specific configurations as evidenced by:

  • References to .env.local in setup scripts
  • Multiple environment variables used throughout the codebase
  • Configuration handling in care.config.ts

Moving the HCX feature flag to environment-specific files would align with the existing configuration patterns and provide better control over where HCX is enabled.

  • Create .env.local for local development
  • Move REACT_ENABLE_HCX from .env to appropriate environment-specific files
  • Consider documenting the environment configuration in README.md
🔗 Analysis chain

Consider environment-specific configuration for HCX feature flag.

Based on the PR discussion about whether to keep HCX in the environment, having REACT_ENABLE_HCX=true in the base .env file will affect all environments. Consider moving this configuration to environment-specific files (e.g., .env.staging, .env.production) to have better control over where HCX is enabled.

Let's check if environment-specific files exist:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for environment-specific .env files
echo "Checking for environment-specific .env files..."
fd -t f "^\.env\." --exclude ".env.example"

Length of output: 356


Script:

#!/bin/bash
# Check for environment-specific .env files including hidden files
echo "Checking for environment-specific .env files..."
fd -H -t f "^\.env\." --exclude ".env.example"

# Also check if there are any references to environment-specific configurations in documentation or config files
echo -e "\nChecking for environment configuration references..."
rg -i "env\." -g "!{.git,node_modules}/*" -g "!*.lock" -g "!*.log"

Length of output: 6657

Comment on lines +123 to +125
clickManagePatientButton() {
cy.verifyAndClickElement("#show-more", "Manage Patient");
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving selector specificity and method consistency.

  1. The #show-more selector is generic and could cause issues if multiple such elements exist on the page.
  2. This method overlaps with the existing clickEditConsultationButton which also clicks "Manage Patient".

Consider these improvements:

  clickManagePatientButton() {
-   cy.verifyAndClickElement("#show-more", "Manage Patient");
+   cy.get("#consultation-buttons")  // Add parent container for better specificity
+     .find("#show-more")
+     .should("contain", "Manage Patient")
+     .click();
+   cy.wait(3000); // Add appropriate wait time or better, wait for a specific element/network request
  }

Also, consider consolidating this with clickEditConsultationButton to avoid duplication of the "Manage Patient" click functionality.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +127 to +132
clickClaimsButton() {
cy.get("#log-update").scrollIntoView();
cy.intercept(/\/api\/hcx\/policy\/\?.*/).as("policyStatus");
cy.get("#consultation-buttons").contains("Claims").click();
cy.wait("@policyStatus").its("response.statusCode").should("eq", 200);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance API handling and test reliability.

The current implementation has several potential reliability issues:

  1. Hard-coded 200 status check might be too strict
  2. API route pattern could be more specific
  3. Missing error handling
  4. No timeout specified for cy.wait

Consider these improvements:

  clickClaimsButton() {
    cy.get("#log-update").scrollIntoView();
-   cy.intercept(/\/api\/hcx\/policy\/\?.*/).as("policyStatus");
+   cy.intercept({
+     method: 'GET',
+     url: '/api/hcx/policy/*'
+   }).as("policyStatus");
    cy.get("#consultation-buttons").contains("Claims").click();
-   cy.wait("@policyStatus").its("response.statusCode").should("eq", 200);
+   cy.wait("@policyStatus", { timeout: 10000 })
+     .then((interception) => {
+       expect(interception.response?.statusCode).to.be.oneOf([200, 201, 204]);
+       // Add additional response validation if needed
+     });
  }
📝 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
clickClaimsButton() {
cy.get("#log-update").scrollIntoView();
cy.intercept(/\/api\/hcx\/policy\/\?.*/).as("policyStatus");
cy.get("#consultation-buttons").contains("Claims").click();
cy.wait("@policyStatus").its("response.statusCode").should("eq", 200);
}
clickClaimsButton() {
cy.get("#log-update").scrollIntoView();
cy.intercept({
method: 'GET',
url: '/api/hcx/policy/*'
}).as("policyStatus");
cy.get("#consultation-buttons").contains("Claims").click();
cy.wait("@policyStatus", { timeout: 10000 })
.then((interception) => {
expect(interception.response?.statusCode).to.be.oneOf([200, 201, 204]);
// Add additional response validation if needed
});
}

Comment on lines 116 to 121
clickViewConsultationButton() {
cy.verifyAndClickElement(
"#view_consulation_updates",
"View Consultation / Consultation Updates",
);
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in selector and consider adding wait handling.

The selector contains a typo: #view_consulation_updates should be #view_consultation_updates. Also, consider adding wait handling after the click if there's a page load or state change.

Apply this diff:

  clickViewConsultationButton() {
    cy.verifyAndClickElement(
-     "#view_consulation_updates",
+     "#view_consultation_updates",
      "View Consultation / Consultation Updates",
    );
+   cy.wait(3000); // Add appropriate wait time or better, wait for a specific element/network request
  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +57 to +64
cy.url().then((url) => {
const urlRegex =
/facility\/([^/]+)\/patient\/([^/]+)\/consultation\/([^/]+)/;
const match = url.match(urlRegex);
if (match) {
consultationId = match[3];
}
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve consultation ID extraction reliability.

The current URL parsing approach could fail silently. Consider adding error handling and type safety.

     cy.url().then((url) => {
       const urlRegex =
         /facility\/([^/]+)\/patient\/([^/]+)\/consultation\/([^/]+)/;
       const match = url.match(urlRegex);
-      if (match) {
+      if (!match) {
+        throw new Error(`Failed to extract consultation ID from URL: ${url}`);
+      }
+      // Type assertion for better type safety
+      const [, facilityId, patientId, extractedConsultationId] = match as RegExpMatchArray;
-        consultationId = match[3];
-      }
+      consultationId = extractedConsultationId;
     });
📝 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
cy.url().then((url) => {
const urlRegex =
/facility\/([^/]+)\/patient\/([^/]+)\/consultation\/([^/]+)/;
const match = url.match(urlRegex);
if (match) {
consultationId = match[3];
}
});
cy.url().then((url) => {
const urlRegex =
/facility\/([^/]+)\/patient\/([^/]+)\/consultation\/([^/]+)/;
const match = url.match(urlRegex);
if (!match) {
throw new Error(`Failed to extract consultation ID from URL: ${url}`);
}
// Type assertion for better type safety
const [, facilityId, patientId, extractedConsultationId] = match as RegExpMatchArray;
consultationId = extractedConsultationId;
});

@@ -139,6 +140,7 @@ export default function HCXPolicyEligibilityCheck({
)}
/>
<ButtonV2
id="check-eligibity"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in button id attribute.

There's a typo in the button's id: "check-eligibity" should be "check-eligibility". This could affect test reliability since Cypress tests will need to use this exact id.

Apply this fix:

-  id="check-eligibity"
+  id="check-eligibility"
📝 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
id="check-eligibity"
id="check-eligibility"

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
.github/workflows/cypress.yaml (2)

21-22: Consider making HCX configuration more flexible

  1. The hard-coded main branch in REACT_ENABLED_APPS could cause issues if the HCX frontend repo changes branches. Consider making it configurable based on the PR target branch.
  2. REACT_ENABLE_HCX is always set to true, but based on the PR discussion about "whether to keep HCX in env", consider making this configurable per environment.

Consider this approach:

-      REACT_ENABLED_APPS: "ohcnetwork/care_hcx_fe@main"
-      REACT_ENABLE_HCX: true
+      REACT_ENABLED_APPS: "ohcnetwork/care_hcx_fe@${{ github.event.pull_request.base.ref }}"
+      REACT_ENABLE_HCX: ${{ github.event.pull_request.base.ref == 'staging' }}

Line range hint 89-91: Consider pinning Chrome version for reproducible tests

The Chrome installation step downloads the latest version, which could lead to inconsistent test behavior across different runs. Consider pinning to a specific version for better reproducibility.

- sudo wget -q https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
+ CHROME_VERSION="119.0.6045.105"
+ sudo wget -q https://dl.google.com/linux/chrome/deb/pool/main/g/google-chrome-stable/google-chrome-stable_${CHROME_VERSION}-1_amd64.deb
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8c9bbc7 and 4d5d3ab.

📒 Files selected for processing (1)
  • .github/workflows/cypress.yaml (1 hunks)
🔇 Additional comments (2)
.github/workflows/cypress.yaml (2)

Line range hint 92-108: LGTM! Well-structured test execution strategy

The separation of forked vs non-forked PR test execution is well implemented with appropriate security considerations. The parallel test execution and artifact handling are properly configured.

Also applies to: 134-150


Line range hint 1-150: Verify HCX test configuration in other environments

The workflow changes appropriately support HCX testing, but we should verify the configuration in other environments.

✅ Verification successful

HCX configuration is appropriately scoped to Cypress tests only

After reviewing all workflow files, I can confirm that the HCX-related environment variables (REACT_ENABLE_HCX and REACT_ENABLED_APPS: "ohcnetwork/care_hcx_fe@main") are correctly configured only in the Cypress test workflow. This is appropriate since:

  1. The configuration is specific to testing environment
  2. No other workflow files require HCX-specific configuration
  3. The deployment workflows handle environment-specific configurations through their respective infrastructure
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any existing HCX configurations in other workflow files
echo "Checking for HCX configurations in other workflow files..."
fd -e yaml -e yml . .github/workflows/ --exec rg -l "REACT_ENABLE_HCX|care_hcx_fe"

# Check for environment-specific configurations
echo "Checking for environment-specific workflow configurations..."
fd -e yaml -e yml . .github/workflows/ --exec rg -l "staging.*environment|production.*environment"

Length of output: 474


Script:

#!/bin/bash
# Let's check all workflow files to understand the environment configurations
echo "=== Listing all workflow files ==="
fd -e yaml -e yml . .github/workflows/ -x cat {}

# Let's also check if there are any environment files that might contain HCX configs
echo "=== Checking for environment files ==="
fd -e env -e env.example . -x cat {}

Length of output: 26411

@nihal467 nihal467 removed the question Further information is requested label Nov 11, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Outside diff range and nitpick comments (5)
cypress/e2e/hcx_spec/HcxClaims.cy.ts (3)

1-7: Standardize import paths for better maintainability.

The imports use a mix of relative (../../pageobject/) and absolute (pageobject/) paths. Consider standardizing to absolute paths throughout.

-import LoginPage from "../../pageobject/Login/LoginPage";
-import { PatientPage } from "../../pageobject/Patient/PatientCreation";
+import LoginPage from "pageobject/Login/LoginPage";
+import { PatientPage } from "pageobject/Patient/PatientCreation";

14-18: Consider moving test data to fixtures.

Hardcoded test data makes tests brittle and harder to maintain. Consider moving these values to a Cypress fixture file.

Create a new file cypress/fixtures/hcx-test-data.json:

{
  "patientName": "Dummy Patient 14",
  "insuranceIdentifier": "insurance-details-0",
  "memberId": "001",
  "policyId": "100",
  "insurerName": "Demo Payor"
}

Then load it in the test:

before(() => {
  cy.fixture('hcx-test-data').as('testData');
});

66-79: Add response schema validation for the eligibility check.

The mock response structure should be validated against a schema to ensure consistency with the API contract.

// Define the schema
const eligibilityResponseSchema = {
  type: 'object',
  required: ['api_call_id', 'correlation_id', 'consultation', 'outcome'],
  properties: {
    api_call_id: { type: 'string', format: 'uuid' },
    correlation_id: { type: 'string', format: 'uuid' },
    timestamp: { type: 'number' },
    consultation: { type: 'string' },
    policy: { type: 'string' },
    outcome: { type: 'string', enum: ['Complete', 'Pending', 'Failed'] },
    limit: { type: 'number' }
  }
};

// Use in the intercept
cy.intercept('POST', '/api/hcx/check_eligibility', (req) => {
  const response = {
    // ... your mock response
  };
  expect(response).to.matchSchema(eligibilityResponseSchema);
  req.reply({ statusCode: 200, body: response });
}).as('checkEligibility');
🧰 Tools
🪛 Gitleaks

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

src/components/Facility/ConsultationCard.tsx (2)

172-172: LGTM! Consider adding data-testid attribute.

The spelling correction in the button's id is good. Since this is being used for testing, consider adding a data-testid attribute as well, which is a more maintainable approach for test selectors.

 <ButtonV2
   id="view_consultation_updates"
+  data-testid="view-consultation-updates-btn"
   className="h-auto whitespace-pre-wrap border border-secondary-500 bg-white text-black hover:bg-secondary-300"

Line range hint 171-183: Enhance accessibility with ARIA attributes.

The button lacks proper accessibility attributes. Consider adding descriptive aria-labels to improve the experience for screen reader users.

 <ButtonV2
   id="view_consultation_updates"
+  aria-label="View consultation details and updates"
   className="h-auto whitespace-pre-wrap border border-secondary-500 bg-white text-black hover:bg-secondary-300"
   onClick={() =>
     navigate(
       `/facility/${itemData.facility}/patient/${itemData.patient}/consultation/${itemData.id}`,
     )
   }
 >
   View Consultation / Consultation Updates
 </ButtonV2>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4d5d3ab and fc4f060.

📒 Files selected for processing (6)
  • cypress/e2e/hcx_spec/HcxClaims.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (0 hunks)
  • cypress/pageobject/Hcx/HcxClaims.ts (1 hunks)
  • cypress/pageobject/Patient/PatientConsultation.ts (2 hunks)
  • src/components/Facility/ConsultationCard.tsx (1 hunks)
  • src/components/HCX/PolicyEligibilityCheck.tsx (2 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/pageobject/Hcx/HcxClaims.ts
  • src/components/HCX/PolicyEligibilityCheck.tsx
🧰 Additional context used
🪛 Gitleaks
cypress/e2e/hcx_spec/HcxClaims.cy.ts

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (5)
cypress/pageobject/Patient/PatientConsultation.ts (2)

123-125: Previous review comment about selector specificity is still applicable

The existing review comment about improving selector specificity and method consistency remains valid.


127-132: 🛠️ Refactor suggestion

Previous review comment about API handling is still applicable with additional concerns

The existing review comment about enhancing API handling remains valid. Additionally:

  1. The API intercept pattern /\/api\/hcx\/policy\/\?.*/ is too loose and could catch unintended requests
  2. Consider using a more specific pattern like:
  clickClaimsButton() {
    cy.get("#log-update").scrollIntoView();
-   cy.intercept(/\/api\/hcx\/policy\/\?.*/).as("policyStatus");
+   cy.intercept({
+     method: 'GET',
+     pathname: '/api/hcx/policy',
+     query: {
+       consultation: '*'  // Add specific query params you expect
+     }
+   }).as("policyStatus");
    cy.get("#consultation-buttons").contains("Claims").click();
-   cy.wait("@policyStatus").its("response.statusCode").should("eq", 200);
+   cy.wait("@policyStatus", { timeout: 10000 })
+     .then((interception) => {
+       expect(interception.response?.statusCode).to.be.oneOf([200, 201, 204]);
+       // Verify response structure
+       expect(interception.response?.body).to.have.property('policies');
+     });
  }
cypress/e2e/hcx_spec/HcxClaims.cy.ts (3)

20-29: LGTM! Good test setup practices.

The test setup follows good practices:

  • Maintains login state using localStorage
  • Properly cleans up filters before each test to prevent interference

94-97: LGTM! Proper test cleanup.

The afterEach hook properly maintains the localStorage state between tests.


57-64: The previous review comment about improving consultation ID extraction is still valid.

Please refer to the previous review comment about adding error handling and type safety to the URL parsing logic.

Comment on lines +116 to +121
clickViewConsultationButton() {
cy.verifyAndClickElement(
"#view_consultation_updates",
"View Consultation / Consultation Updates",
);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add wait handling after click action

The click action might trigger page load or state changes. Add appropriate wait handling to improve test reliability.

  clickViewConsultationButton() {
    cy.verifyAndClickElement(
      "#view_consultation_updates",
      "View Consultation / Consultation Updates",
    );
+   // Wait for the consultation updates to load
+   cy.get('.consultation-updates-container').should('be.visible', { timeout: 10000 });
  }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +31 to +92
it("Verify the HCX Workflow for a patient with mocked eligibility", () => {
// Modify the insurance for a facility
patientPage.visitPatient(hcxPatientName);
patientConsultationPage.clickPatientDetails();
patientPage.clickPatientUpdateDetails();
patientInsurance.clickAddInsruanceDetails();
patientInsurance.typePatientInsuranceDetail(
firstInsuranceIdentifier,
"subscriber_id",
patientMemberId,
);
patientInsurance.typePatientInsuranceDetail(
firstInsuranceIdentifier,
"policy_id",
patientPolicyId,
);
patientInsurance.selectPatientInsurerName(
firstInsuranceIdentifier,
patientInsurerName,
);
cy.submitButton("Save Details");
cy.verifyNotification("Patient updated successfully");
cy.closeNotification();
// Navigate to Consultation View and capture dynamic consultation ID
let consultationId: string;
patientConsultationPage.clickViewConsultationButton();
cy.url().then((url) => {
const urlRegex =
/facility\/([^/]+)\/patient\/([^/]+)\/consultation\/([^/]+)/;
const match = url.match(urlRegex);
if (match) {
consultationId = match[3];
}
});
// Intercept and mock the eligibility check response using captured consultationId
cy.intercept("POST", "/api/hcx/check_eligibility", (req) => {
req.reply({
statusCode: 200,
body: {
api_call_id: "bfa228f0-cdfa-4426-bebe-26e996079dbb",
correlation_id: "86ae030c-1b33-4e52-a6f1-7a74a48111eb",
timestamp: Date.now(),
consultation: consultationId,
policy: patientPolicyId,
outcome: "Complete",
limit: 1,
},
});
}).as("checkEligibility");
// Raise a HCX Pre-auth
patientConsultationPage.clickManagePatientButton();
patientConsultationPage.clickClaimsButton();
hcxClaims.selectEligiblePolicy(patientInsurerName);
hcxClaims.verifyPolicyEligibility();
cy.verifyNotification("Checking Policy Eligibility");
cy.closeNotification();
// Confirm that the eligibility check displays as successful
cy.wait("@checkEligibility").then((interception) => {
const response = interception.response.body;
expect(response.outcome).to.equal("Complete");
});
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider breaking down the test into smaller, focused scenarios.

The current test covers multiple aspects of the workflow in a single test. This makes it harder to maintain and debug failures.

Consider splitting into separate test cases:

it('should update patient insurance details')
it('should capture consultation ID from URL')
it('should verify policy eligibility check')
🧰 Tools
🪛 Gitleaks

70-70: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

@khavinshankar khavinshankar merged commit fe82a57 into develop Nov 12, 2024
58 checks passed
@khavinshankar khavinshankar deleted the hcx-develop branch November 12, 2024 00:17
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! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add cypress test for HCX workflow
2 participants