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

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

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

    • Added a new environment variable for local development server configuration.
    • Enhanced test coverage for patient consultation creation and discharge processes.
    • Improved user creation and management tests with detailed error handling.
  • Bug Fixes

    • Removed unnecessary wait commands across various test cases to enhance responsiveness and efficiency.
  • Documentation

    • Updated success notification messages for clarity in inventory management tests.
  • Refactor

    • Streamlined test methods by removing static wait times and implementing visibility checks for UI elements.

@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 f8cd9c8
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672e83c14318b900087a09ad
😎 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
@@ -43,7 +45,6 @@ describe("Inventory Management Section", () => {
// verify the last entry deletion
facilityPage.verifyStockInRow("#row-0", "Added Stock");
facilityPage.verifyStockInRow("#row-1", "Used Stock");
cy.wait(3000);
Copy link
Member

Choose a reason for hiding this comment

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

the intercept and API Verification is missing here

@@ -59,7 +60,6 @@ describe("Inventory Management Section", () => {
facilityPage.verifyBadgeWithText(".badge-danger", "Low Stock");
// modify with manual minimum badge
facilityPage.clickAddMinimumQuanitity();
cy.wait(3000);
Copy link
Member

Choose a reason for hiding this comment

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

the intercept and API Verification is missing here

@@ -8,6 +8,7 @@ REACT_PUBLIC_URL=https://care.ohc.network

# Care API URL without the /api prefix
REACT_CARE_API_URL=https://careapi.ohc.network
# REACT_CARE_API_URL=http://localhost:9000
Copy link
Member

Choose a reason for hiding this comment

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

revert this change

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 various modifications primarily focused on Cypress end-to-end test files and the .env configuration. Changes include the addition of a commented environment variable for local development, the removal of hardcoded wait commands in multiple test cases to improve responsiveness, and enhancements to test logic for better error handling and verification. Additionally, new methods were added to the FacilityCreation page object to improve functionality related to facility management.

Changes

File Path Change Summary
.env Added a commented line for REACT_CARE_API_URL pointing to a local development server.
cypress/e2e/assets_spec/AssetHomepage.cy.ts Removed cy.wait(2000); from the "Export asset" test case.
cypress/e2e/facility_spec/FacilityCreation.cy.ts Changed triageDate from "02122023" to "03122023".
cypress/e2e/facility_spec/FacilityInventory.cy.ts Updated success notification messages and removed cy.wait(3000); from two test cases.
cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts Added new test cases for various patient consultation types and improved error handling.
cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts Added new test cases for discharging patients with different reasons and improved input handling.
cypress/e2e/patient_spec/PatientLogUpdate.cy.ts Enhanced creation and editing of patient log updates with improved error handling.
cypress/e2e/users_spec/UsersCreation.cy.ts Added new test cases for user profile updates and mandatory field errors, removed cy.wait(2000);.
cypress/pageobject/Facility/FacilityCreation.ts Added new methods for middleware management and updated existing methods for better UI interaction.
cypress/pageobject/Patient/PatientCreation.ts Removed static wait from visitPatient method and updated clickCreatePatient for API response validation.
cypress/pageobject/Patient/PatientDoctorNotes.ts Removed cy.wait(2000); from addDiscussionNotes method.
cypress/pageobject/Patient/PatientFileupload.ts Updated recordAudio method to remove fixed waits and ensure actions are only executed when buttons are enabled.
cypress/pageobject/Patient/PatientLogupdate.ts Removed multiple cy.wait(2000) calls from various methods.
cypress/pageobject/Patient/PatientPrescription.ts Updated enterDiscontinueReason method to use visibility check instead of static wait.
cypress/pageobject/Patient/PatientTransfer.ts Removed cy.wait(2000); from clickTransferSubmitButton and clickConsultationCancelButton.
cypress/pageobject/Users/ManageUserPage.ts Updated clickCloseSlideOver to include a visibility check before clicking.

Assessment against linked issues

Objective Addressed Explanation
Replace hardcoded cy.wait() with cy.intercept in Cypress files (#8925)

Possibly related PRs

  • Improve code splitting #8979: The changes in this PR involve modifications to environment handling, including the removal of the .envrc file, which is related to the .env file changes in the main PR where a new commented line for REACT_CARE_API_URL was added.
  • Fixed the Typo Issue in the district admin cypress function #9023: This PR corrects a typo in the method name related to logging in as a district admin, which is relevant to the overall functionality and testing environment that may utilize the .env settings, although it does not directly modify the same files or variables.

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • Jacobjeevan
  • shivankacker
  • bodhish

Poem

In the land of tests, we hop and play,
Removing waits, making things sway.
With new paths in code, we leap with glee,
For every change, a better spree!
Hopping through functions, so light and spry,
Our tests now dance, oh me, oh my! 🐇✨


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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
changes required merge conflict pull requests with merge conflict test failed
Projects
None yet
Development

Successfully merging this pull request may close these issues.

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