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

    • Introduced new methods for intercepting and verifying API calls in user management, patient discharge, and consultation processes.
    • Enhanced localization with new entries in the language file.
    • Added new test cases for patient consultation scenarios and improved coverage for facility creation and inventory management.
  • Bug Fixes

    • Improved error handling and response verification across various test cases, ensuring accurate status checks.
  • Documentation

    • Updated comments for clarity in several test cases.
  • Chores

    • Removed static wait commands in favor of dynamic checks to enhance test execution efficiency.

@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 c951801
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/675d9fc74d6d500008774aed
😎 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
@@ -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 comprehensive modifications to Cypress end-to-end test files across multiple components, focusing on replacing hardcoded cy.wait() commands with dynamic cy.intercept() methods. The changes span patient, facility, user, and asset management test suites, enhancing test reliability by implementing more robust API request interception and verification techniques. The modifications aim to reduce test flakiness and improve the overall responsiveness of the test execution.

Changes

File Path Change Summary
cypress/e2e/facility_spec/* Updated test files with improved API interception for facility-related actions
cypress/e2e/patient_spec/* Enhanced patient management tests with dynamic API request handling
cypress/pageobject/Patient/* Added intercept methods for consultation, discharge, and prescription workflows
cypress/pageobject/Users/* Introduced API interception for user creation and profile updates
public/locale/en.json Added localization key for "unassign"

Assessment against linked issues

Objective Addressed Explanation
Replace hardcoded cy.wait() Systematically replaced static waits with cy.intercept() across multiple test files
Reduce test flakiness Implemented dynamic waiting mechanisms tied to API response status

Possibly related PRs

  • Rewriting UsersCreation.cy.ts according to POM approach #8930: This PR refactors the UsersCreation.cy.ts file to improve its structure and readability, which may relate to the overall organization of test files, similar to the changes made in the main PR for FacilityCreation.cy.ts.
  • Avatar in UserAutoComplete #8967: Although this PR focuses on user management, it introduces new methods and improvements that could indirectly relate to the notification checks added in the main PR, as both involve user interactions and feedback mechanisms.
  • Facility bed capacity verification test #9145: This PR enhances the FacilityCreation.cy.ts file by introducing structured data objects for facility management, which aligns with the main PR's focus on improving test clarity and maintainability.
  • Fixed the flaky test in user skill management cypress test #9148: This PR addresses a flaky test in user skill management, which may relate to the notification verification aspect introduced in the main PR, as both involve ensuring reliable user interactions.
  • Users Manage Test Fix #9368: This PR introduces a new test case for verifying working hours in user profiles, which could relate to the verification steps added in the main PR, as both focus on ensuring accurate feedback in user management scenarios.

Suggested labels

needs review, tested

Suggested reviewers

  • rithviknishad
  • nihal467

Poem

🐰 Hop, hop, through the code we go,
Replacing waits with intercepts' flow
No more static delays so slow
Our tests now dance with API's glow! 🚀
Cypress tests, now swift and bright ✨

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


📜 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 559f5a7 and c951801.

📒 Files selected for processing (2)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts (1 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cypress/e2e/facility_spec/FacilityCreation.cy.ts
  • cypress/pageobject/Facility/FacilityCreation.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

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

🧹 Outside diff range and nitpick comments (13)
cypress/pageobject/Users/UserCreation.ts (2)

52-54: Consider adding response body validation

While the interception is correctly implemented, consider adding response body validation to ensure the created user data matches the expected format.

   interceptCreateUser() {
-    cy.intercept("POST", "/api/v1/users/add_user/").as("createUser");
+    cy.intercept("POST", "/api/v1/users/add_user/", (req) => {
+      req.reply((res) => {
+        expect(res.statusCode).to.equal(201);
+        expect(res.body).to.have.property('id');
+        expect(res.body).to.have.property('username');
+      });
+    }).as("createUser");
   }

56-58: Consider handling error scenarios

The verification method only checks for successful creation. Consider adding error handling for failed user creation attempts.

   verifyCreateUser() {
-    cy.wait("@createUser").its("response.statusCode").should("eq", 201);
+    cy.wait("@createUser").then((interception) => {
+      if (interception.response?.statusCode === 201) {
+        expect(interception.response.body).to.exist;
+      } else {
+        throw new Error(`User creation failed: ${interception.response?.body?.message || 'Unknown error'}`);
+      }
+    });
   }
cypress/pageobject/Users/UserProfilePage.ts (1)

18-20: Add specific error messages for update failures

Consider enhancing the verification method with more specific error handling and response validation.

   verifyUpdateUsersResponse() {
-    cy.wait("@updateUser").its("response.statusCode").should("eq", 200);
+    cy.wait("@updateUser").then((interception) => {
+      const response = interception.response;
+      if (response?.statusCode !== 200) {
+        throw new Error(
+          `Failed to update user: ${response?.body?.detail || 'Unknown error'}`
+        );
+      }
+      // Verify expected response structure
+      expect(response.body).to.have.property('updated_at');
+    });
   }
cypress/e2e/users_spec/UsersCreation.cy.ts (3)

111-113: Consider enhancing API interception with payload verification.

The encapsulation of API interception in page objects is a good practice. However, consider adding payload verification to ensure the correct data is being sent to the API.

Example enhancement in UserProfilePage:

interceptUpdateUsers() {
  return cy.intercept("PATCH", "/api/v1/users/*").as("updateUser");
}

verifyUpdateUsersResponse() {
  cy.wait("@updateUser").then((interception) => {
    // Verify response status
    expect(interception.response.statusCode).to.eq(200);
    
    // Verify request payload contains required fields
    expect(interception.request.body).to.have.property('first_name');
    expect(interception.request.body).to.have.property('last_name');
    expect(interception.request.body).to.have.property('phone_number');
  });
}

161-163: Consider adding error handling for API failures.

The encapsulation of user creation API interception is good. However, consider adding explicit error handling to make the test more robust.

Example enhancement in UserCreationPage:

interceptCreateUser() {
  return cy.intercept("POST", "/api/v1/users/add_user/").as("createUser");
}

verifyCreateUser() {
  cy.wait("@createUser").then((interception) => {
    // Handle different response scenarios
    if (interception.response.statusCode === 200) {
      expect(interception.response.body).to.have.property('id');
    } else {
      // Handle error responses
      throw new Error(`User creation failed: ${interception.response.body.message}`);
    }
  });
}

Line range hint 1-201: Consider architectural improvements for better maintainability.

While the test structure is good, consider these improvements:

  1. Split the test file into smaller, focused files (e.g., UserProfileUpdate.cy.ts, UserCreation.cy.ts)
  2. Move test data to fixtures
  3. Add type definitions for API responses

Example structure:

// types/api.d.ts
interface UserResponse {
  id: string;
  username: string;
  first_name: string;
  // ... other fields
}

// fixtures/test-data.json
{
  "userProfile": {
    "firstName": "District Editted",
    "lastName": "Cypress",
    // ... other test data
  }
}

// Import in test
import testData from '../fixtures/test-data.json';
cypress/pageobject/Patient/PatientLogupdate.ts (3)

7-12: Consider enhancing API intercept implementations.

While the separation of intercept setup and verification is good, there are opportunities for improvement:

  1. URL patterns could be more specific to prevent unintended matches
  2. Response verification could be more comprehensive
  3. Similar methods could be grouped together

Consider applying these improvements:

+ // API Intercept Methods
  interceptConsultationBed() {
-   cy.intercept("GET", "**/api/v1/consultationbed/*").as("getBed");
+   cy.intercept("GET", "**/api/v1/consultationbed/**").as("getBed");
  }

  verifyConsultationBed() {
-   cy.wait("@getBed").its("response.statusCode").should("eq", 200);
+   cy.wait("@getBed").then((interception) => {
+     expect(interception.response.statusCode).to.eq(200);
+     expect(interception.response.body).to.not.be.null;
+   });
  }

  interceptDailyRounds() {
    cy.intercept("GET", "**/api/v1/consultation/*/daily_rounds/*/").as(
      "getDailyRounds",
    );
  }

  // ... similar improvements for other intercept methods

Also applies to: 89-97, 99-107


112-128: Enhance view/update operations with proper UI state verification.

The log update operations could benefit from additional UI state verifications to prevent potential race conditions.

Consider enhancing the implementations:

  clickLogUpdateViewDetails(element: string, patientCategory: string) {
    cy.get(element).scrollIntoView();
    cy.verifyContentPresence(element, [patientCategory]);
    this.interceptDailyRounds();
-   cy.get(element).first().contains("View Details").click();
+   cy.get(element)
+     .first()
+     .contains("View Details")
+     .should("be.visible")
+     .and("be.enabled")
+     .click();
    this.verifyDailyRounds();
+   // Verify the details view is loaded
+   cy.get(".details-container").should("be.visible");
  }

Similar improvements can be applied to clickLogUpdateUpdateLog and clickUpdateDetail methods.


Line range hint 1-180: Overall implementation successfully addresses PR objectives.

The changes effectively replace hardcoded cy.wait() commands with proper API intercepts, which aligns perfectly with the PR's goal of reducing test flakiness. The implementation:

  • Follows a consistent pattern for API interceptions
  • Maintains clear separation of concerns
  • Provides better test reliability through proper wait conditions

Consider documenting these patterns in your testing guidelines to ensure consistent implementation across the codebase.

cypress/pageobject/Patient/PatientDischarge.ts (1)

46-48: Consider enhancing error handling.

While the implementation is correct, consider adding error handling for non-200 status codes to provide better debugging information.

 verifyDischargePatient() {
-  cy.wait("@postDischarge").its("response.statusCode").should("eq", 200);
+  cy.wait("@postDischarge").then((interception) => {
+    if (interception.response?.statusCode !== 200) {
+      cy.log(`Discharge failed with status: ${interception.response?.statusCode}`);
+      cy.log(`Response body: ${JSON.stringify(interception.response?.body)}`);
+    }
+    expect(interception.response?.statusCode).to.equal(200);
+  });
 }
cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts (1)

Line range hint 1-400: Consider extending the intercept pattern to other API calls

The file has several other API interactions that could benefit from the same robust intercept pattern you've implemented for prescriptions and consultation edits. For example:

  • Patient creation
  • Investigation addition
  • Consultation creation
  • Shift request creation

Would you like help identifying specific locations where this pattern could be applied?

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

447-449: Standardize intercept URL patterns

The intercept URL pattern in interceptMinimumQuantity() includes a leading **/, whereas other intercepts in the codebase do not. For consistency, consider removing the leading **/ to match the pattern used in other intercepts.

Apply this diff to standardize the intercept URL pattern:

-    cy.intercept("GET", "**/api/v1/facility/*/min_quantity/**").as(
+    cy.intercept("GET", "/api/v1/facility/*/min_quantity/**").as(
cypress/e2e/facility_spec/FacilityInventory.cy.ts (1)

39-41: Rephrase success notification message for clarity

The success notification message "Inventory use stock updated successfully" could be clearer. Consider rephrasing it to "Inventory used stock updated successfully" or "Inventory stock usage updated successfully" for better clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1099d9a and 1ccab9c.

📒 Files selected for processing (16)
  • cypress/e2e/facility_spec/FacilityInventory.cy.ts (2 hunks)
  • cypress/e2e/patient_spec/PatientConsultationCreation.cy.ts (2 hunks)
  • cypress/e2e/patient_spec/PatientConsultationDischarge.cy.ts (4 hunks)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts (1 hunks)
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts (6 hunks)
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts (2 hunks)
  • cypress/e2e/users_spec/UsersCreation.cy.ts (2 hunks)
  • cypress/pageobject/Facility/FacilityCreation.ts (3 hunks)
  • cypress/pageobject/Patient/PatientConsultation.ts (1 hunks)
  • cypress/pageobject/Patient/PatientCreation.ts (3 hunks)
  • cypress/pageobject/Patient/PatientDischarge.ts (2 hunks)
  • cypress/pageobject/Patient/PatientLogupdate.ts (3 hunks)
  • cypress/pageobject/Patient/PatientPrescription.ts (2 hunks)
  • cypress/pageobject/Users/UserCreation.ts (1 hunks)
  • cypress/pageobject/Users/UserProfilePage.ts (1 hunks)
  • cypress/pageobject/utils/paginationHelpers.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
  • cypress/e2e/patient_spec/PatientHomepage.cy.ts
  • cypress/e2e/patient_spec/PatientRegistration.cy.ts
  • cypress/e2e/patient_spec/PatientLogUpdate.cy.ts
  • cypress/pageobject/Patient/PatientPrescription.ts
  • cypress/pageobject/Patient/PatientConsultation.ts
🔇 Additional comments (11)
cypress/pageobject/utils/paginationHelpers.ts (1)

21-23: LGTM: Proper implementation of dynamic wait

The verifyPatientNavigation method correctly implements the dynamic wait pattern by checking the response status code.

cypress/pageobject/Users/UserProfilePage.ts (1)

14-16: LGTM: Good use of wildcard pattern

The interceptUpdateUsers method correctly uses a wildcard pattern for the user ID, making it flexible for different user updates.

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

9-21: LGTM! Well-structured implementation of dynamic waits.

The refactored code properly handles different discharge reasons with appropriate API intercepts and status code verifications, replacing hardcoded waits with dynamic ones.


40-44: LGTM! Clean implementation of discharge API interception.

The function follows the established pattern for API interceptions in the codebase.

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

189-211: LGTM! Good implementation of visibility checks.

The function properly ensures element visibility before performing assertions, which helps prevent flaky tests.


102-104: 🛠️ Refactor suggestion

Complete the API verification implementation.

The function intercepts the API but doesn't verify the status code, which is inconsistent with other similar implementations in the codebase.

 clickCancelButton() {
   cy.intercept("GET", "**/api/v1/patient/*/").as("getPatient");
   cy.get("#cancel").click();
-  cy.wait("@getPatient");
+  cy.wait("@getPatient").its("response.statusCode").should("eq", 200);
 }

Likely invalid or redundant comment.

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

107-109: Great implementation of dynamic waiting pattern!

The sequence of intercepting the prescription API, triggering the action, and then verifying the response is a robust approach that replaces hardcoded waits. This change aligns well with Cypress best practices for handling API requests.


380-382: Verify the robustness of the consultation edit flow

While the implementation follows good practices by using intercepts instead of hardcoded waits, let's ensure the edit form is properly populated before proceeding with changes.

✅ Verification successful

The consultation edit flow is properly implemented with necessary wait conditions

The implementation is robust because:

  • The interceptConsultation() call sets up the intercept before clicking the edit button
  • The verifyConsultation() method includes a cy.wait("@getConsultation") that ensures the API call completes with a 200 status code
  • The subsequent test actions (like typing illness history and selecting diagnosis) only proceed after this verification
  • This pattern is consistently used across multiple test files showing it's a proven approach
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any existing cy.wait calls in the consultation edit flow
# that might indicate timing issues, and look for form population patterns.

# Search for any remaining cy.wait calls in consultation edit flows
rg -A 5 "cy\.wait.*edit.*consultation" 

# Look for form population patterns after clicking edit
rg -A 10 "clickEditConsultationButton|verifyConsultation"

Length of output: 11180

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

339-340: Avoid using generic IDs like id in selectors

Using div#id as a selector may lead to unintended behavior if multiple elements share the generic ID id. Please use a more specific and unique ID to target the desired element.

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

28-30: Improved test reliability with intercepts and verifications

Good job adding interceptManageInventoryItem() and verifyManageInventoryItem() to ensure the network requests are properly intercepted and validated, enhancing test reliability.


64-67: Enhanced test reliability by adding intercepts and verifications

Adding interceptMinimumQuantity() and verifyMinimumQuantity() improves the test by ensuring the API calls are intercepted and responses are validated.

cypress/pageobject/utils/paginationHelpers.ts Outdated Show resolved Hide resolved
cypress/pageobject/Patient/PatientCreation.ts Outdated Show resolved Hide resolved
@Rishith25 Rishith25 requested a review from nihal467 December 11, 2024 04:45
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 11, 2024
Copy link

👋 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 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 (2)
cypress/pageobject/Users/ManageUserPage.ts (2)

219-221: Consider using a more specific URL pattern

While the implementation is good, the URL pattern could be more specific to avoid intercepting unintended requests.

-    cy.intercept("GET", "**/api/v1/users/*/skill").as("getUserSkill");
+    cy.intercept("GET", "/api/v1/users/*/skill").as("getUserSkill");

223-225: Consider adding response body validation

While status code verification is good, consider adding response body structure validation for more robust testing.

-    cy.wait("@getUserSkill").its("response.statusCode").should("eq", 200);
+    cy.wait("@getUserSkill").then((interception) => {
+      expect(interception.response?.statusCode).to.eq(200);
+      expect(interception.response?.body).to.have.property("skills");
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between eee4f1a and c16381c.

📒 Files selected for processing (4)
  • cypress/e2e/users_spec/UsersCreation.cy.ts (2 hunks)
  • cypress/e2e/users_spec/UsersManage.cy.ts (1 hunks)
  • cypress/pageobject/Users/ManageUserPage.ts (3 hunks)
  • cypress/pageobject/Users/UserCreation.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • cypress/pageobject/Users/UserCreation.ts
  • cypress/e2e/users_spec/UsersManage.cy.ts
  • cypress/e2e/users_spec/UsersCreation.cy.ts
🔇 Additional comments (1)
cypress/pageobject/Users/ManageUserPage.ts (1)

11-13: LGTM! Well-implemented API interception

The implementation correctly replaces hardcoded waits with proper API interception and response validation for the skills endpoint.

cypress/pageobject/Users/ManageUserPage.ts Show resolved Hide resolved
cypress/pageobject/Users/ManageUserPage.ts Show resolved Hide resolved
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 11, 2024
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 11, 2024
Copy link

👋 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 removed the merge conflict pull requests with merge conflict label Dec 13, 2024
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.

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