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

Added cypress tests for Facility cover image button functionality #9134

Closed
wants to merge 4 commits into from

Conversation

rohitlingarker
Copy link

@rohitlingarker rohitlingarker commented Nov 15, 2024

Proposed Changes

  • Fixes Refactor the existing cypress test to upload cover image #9109
  • Added functions (verifyCoverImageModalClosed, clickDeleteCoverImage) and cypress Intercepts to api calls in pageobject/Facility/FacilityManage.ts.
  • Written tests using the already existing functions to test upload, edit and deletion of facility cover image in FacilityManage.cy.ts.
  • Added roles in the FacilityManage.cy.ts for testing the functionality across different user roles
  • Added id = "delete-cover-page" to the delete cover page button element.

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new test suite for "Facility Cover Image Functionality" to enhance testing coverage.
    • Added methods to improve the functionality of the Facility Management interface, including handling cover image uploads and deletions.
  • Bug Fixes

    • Removed a non-functional test case related to the "Facility Cover Image" button to streamline testing.
  • Improvements

    • Enhanced accessibility of the Avatar Edit Modal with new id attributes for buttons, improving integration with testing frameworks.

Copy link
Contributor

coderabbitai bot commented Nov 15, 2024

Walkthrough

This pull request introduces a new Cypress test suite for the "Facility Cover Image Functionality," enhancing the testing framework for facility management. It adds a structured approach to test various user roles and their interactions with the cover image modal, including uploading, editing, and deleting images. Additionally, it removes a previously non-functional test case related to the cover image button. Updates to the FacilityManage class include new methods for handling modal interactions, while the AvatarEditModal component receives accessibility improvements through added id attributes.

Changes

File Path Change Summary
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts Introduced a new test suite for facility cover image functionality, including user role tests and modal interactions.
cypress/e2e/facility_spec/FacilityManage.cy.ts Removed a non-functional test case related to the cover image button.
cypress/pageobject/Facility/FacilityManage.ts Added methods for handling modal interactions: clickCancelButton, verifyCoverImageModalClosed, clickDeleteCoverImage. Updated clickSaveCoverImage with API intercept.
src/components/Common/AvatarEditModal.tsx Added id attributes to delete and save buttons for improved accessibility.

Assessment against linked issues

Objective Addressed Explanation
Enhance the existing test suite to include functionality for uploading, editing, and deleting the facility cover image. (#9109)
Add API request verification wherever required using cy.intercept(); (#9109)
Add the tests in the facilityManage.cy.ts file and any new page objects in the facilityManage.ts file. (#9109)
Verify the functionality of the cancel button in the cover image modal. (#9109)
Confirm the API response after uploading, editing, and deleting the cover image. (#9109)

Possibly related PRs

Suggested labels

tested, needs review

Suggested reviewers

  • nihal467
  • khavinshankar

Poem

In the realm of tests, we hop with glee,
Cover images now dance, as bright as can be.
With buttons to click and modals to see,
Our Cypress suite shines, as fun as a spree!
So let’s test away, with joy in our hearts,
For every new feature, a fresh start imparts! 🐰✨

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 (1.23.1)

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

cypress/e2e/facility_spec/FacilityCoverImage.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 15, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit f910767
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/6743ec934dae800008bc8411
😎 Deploy Preview https://deploy-preview-9134--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.

@rohitlingarker rohitlingarker changed the title Added cypress tests for Facility cover image button functionality closes # Added cypress tests for Facility cover image button functionality closes #9109 Nov 15, 2024
@rohitlingarker rohitlingarker changed the title Added cypress tests for Facility cover image button functionality closes #9109 Added cypress tests for Facility cover image button functionality Nov 15, 2024
@nihal467
Copy link
Member

@rohitlingarker since the PR is under draft removing the review PR

@nihal467 nihal467 self-assigned this Nov 19, 2024
@khavinshankar
Copy link
Member

We should consider making each test atomic i.e., 1 test shouldn't influence the other, as this is making debugging and developing harder. We should clean up after or during each test and create the necessary resources before or during the test. There is no need to refactor anything for now, maybe we should enforce this for newer tests.

@nihal467 thoughts?

@nihal467
Copy link
Member

nihal467 commented Nov 20, 2024

@rohitlingarker

  • Create a new test file under the facility_spec folder itself.
  • Dynamically select a new facility for each user in the test, making sure that the same set of code and logic runs for different users in different facilities.

this way like @khavinshankar mention they will be independent test

@nihal467 nihal467 removed their assignment Nov 20, 2024
@rohitlingarker rohitlingarker marked this pull request as ready for review November 25, 2024 03:37
@rohitlingarker rohitlingarker requested a review from a team as a code owner November 25, 2024 03:37
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: 8

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

4-7: Consider improving test data management

The hard-coded facility names could make tests brittle and harder to maintain. Consider:

  1. Moving test data to a separate fixture file
  2. Adding TypeScript interfaces for better type safety
+interface UserFacility {
+  username: string;
+  facilityName: string;
+}
+
-const roleUserFacilities = [
+const roleUserFacilities: UserFacility[] = [
   { username: "devdistrictadmin", facilityName: "Dummy Facility 40" },
   { username: "devdoctor", facilityName: "Dummy Facility 4" },
 ];
cypress/pageobject/Facility/FacilityManage.ts (1)

1-1: Consider adding test data management methods

Based on the PR objectives emphasizing test atomicity and proper test data management, consider adding methods to this page object for:

  1. Creating a new facility with cover image for testing
  2. Cleaning up test data after each test
  3. Verifying the state of cover image data

This will help ensure tests are truly independent and maintain their own test data.

src/components/Common/AvatarEditModal.tsx (2)

Line range hint 291-303: Consider adding test IDs to other interactive elements.

While the save and delete buttons now have IDs, other interactive elements could benefit from similar identifiers to maintain consistent testability. Consider adding test IDs to:

  • Upload image label/input
  • Camera open button
  • Cancel button
  • Switch camera button
  • Capture button

Example additions:

 <label
-  id="upload-cover-image"
+  id="upload-cover-image-label"
   className="button-size-default button-shape-square button-primary-default inline-flex h-min w-full cursor-pointer items-center justify-center gap-2 whitespace-pre font-medium shadow outline-offset-1 transition-all duration-200 ease-in-out enabled:hover:shadow-md disabled:cursor-not-allowed disabled:bg-secondary-200 disabled:text-secondary-500"
 >
   <input
+    id="upload-cover-image-input"
     title="changeFile"
     type="file"
     accept="image/*"
     className="hidden"
     onChange={onSelectFile}
   />
 </label>

Line range hint 1-450: Enhance accessibility attributes for better user experience.

While reviewing the component for testing improvements, I noticed some accessibility enhancements that could be made:

  1. Add aria-labels to buttons and inputs
  2. Add role attributes where appropriate
  3. Add aria-live regions for status updates

Example improvements:

 <ButtonV2
   id="delete-cover-image"
+  aria-label={`${t("delete")} ${t("cover_image")}`}
   onClick={deleteAvatar}
   disabled={isProcessing}
 >
   {t("delete")}
 </ButtonV2>

 <div 
+  role="status"
+  aria-live="polite"
   className="flex flex-col gap-2 pt-4 sm:flex-row"
 >
   {isProcessing ? `${t("uploading")}...` : null}
 </div>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2fdffa2 and f910767.

⛔ Files ignored due to path filters (3)
  • cypress/fixtures/facility-cover-image.jpg is excluded by !**/*.jpg
  • cypress/fixtures/facility-cover-image1.jpg is excluded by !**/*.jpg
  • cypress/fixtures/new-facility-cover-image.jpg is excluded by !**/*.jpg
📒 Files selected for processing (4)
  • cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1 hunks)
  • cypress/e2e/facility_spec/FacilityManage.cy.ts (0 hunks)
  • cypress/pageobject/Facility/FacilityManage.ts (2 hunks)
  • src/components/Common/AvatarEditModal.tsx (1 hunks)
💤 Files with no reviewable changes (1)
  • cypress/e2e/facility_spec/FacilityManage.cy.ts
🔇 Additional comments (3)
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1)

1-56: Verify alignment with PR objectives

The implementation aligns with the comment suggestions to create a new test file, but some requirements from the PR objectives need attention:

  1. API intercepts are missing (addressed in previous comments)
  2. Test atomicity could be improved with better cleanup
  3. Consider adding more specific test cases for different user roles beyond just verifying the same workflow
cypress/pageobject/Facility/FacilityManage.ts (1)

17-17: LGTM!

Good addition of scrollIntoView() to ensure the element is in the viewport before checking visibility.

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

Line range hint 286-290: LGTM! The added button ID enhances testability.

The addition of id="delete-cover-image" aligns with the PR objectives and facilitates Cypress test selection.

Comment on lines +14 to +17
before(() => {
cy.loginByApi(username, "Coronasafe@123");
cy.saveLocalStorage();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for login failures

The login step should handle potential failures gracefully.

 before(() => {
-  cy.loginByApi(username, "Coronasafe@123");
+  cy.loginByApi(username, "Coronasafe@123").then((response) => {
+    expect(response.status).to.eq(200);
+  });
   cy.saveLocalStorage();
 });
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
before(() => {
cy.loginByApi(username, "Coronasafe@123");
cy.saveLocalStorage();
});
before(() => {
cy.loginByApi(username, "Coronasafe@123").then((response) => {
expect(response.status).to.eq(200);
});
cy.saveLocalStorage();
});

Comment on lines +29 to +50
it("Facility Cover Image button functionality", () => {
// It's only button functionality because we can't access S3 bucket in local
// Check: Cancel button functionality
facilityManage.clickCoverImage();
facilityManage.clickCancelButton();
facilityManage.verifyCoverImageModalClosed();
// Check: upload an image, verifying the API response.
facilityManage.clickCoverImage();
facilityManage.verifyUploadButtonVisible();
facilityManage.uploadCoverImage("facility-cover-image.jpg");
facilityManage.clickSaveCoverImage();
facilityManage.verifyCoverImageModalClosed();
// //Check: Edit the current cover image by uploading a new one, and verify the API response.
facilityManage.clickCoverImage();
facilityManage.verifyUploadButtonVisible();
facilityManage.uploadCoverImage("new-facility-cover-image.jpg");
facilityManage.clickSaveCoverImage();
facilityManage.verifyCoverImageModalClosed();
//Check: Delete the existing cover image, confirming the API response.
facilityManage.clickCoverImage();
facilityManage.clickDeleteCoverImage();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance test assertions and API verifications

The test case lacks proper assertions after API calls and UI state verifications.

Add assertions and API verifications:

 it("Facility Cover Image button functionality", () => {
-  // It's only button functionality because we can't access S3 bucket in local
+  // Note: This test verifies UI interactions and API calls without actual S3 bucket operations
+  // as S3 access is not available in local development environment
   
   // Check: Cancel button functionality
   facilityManage.clickCoverImage();
   facilityManage.clickCancelButton();
   facilityManage.verifyCoverImageModalClosed();
   
   // Check: upload an image, verifying the API response.
   facilityManage.clickCoverImage();
   facilityManage.verifyUploadButtonVisible();
   facilityManage.uploadCoverImage("facility-cover-image.jpg");
   facilityManage.clickSaveCoverImage();
+  cy.wait('@uploadCoverImage').its('response.statusCode').should('eq', 200);
   facilityManage.verifyCoverImageModalClosed();
+  facilityManage.verifyCoverImageVisible();
   
   // Check: Edit the current cover image
   facilityManage.clickCoverImage();
   facilityManage.verifyUploadButtonVisible();
   facilityManage.uploadCoverImage("new-facility-cover-image.jpg");
   facilityManage.clickSaveCoverImage();
+  cy.wait('@uploadCoverImage').its('response.statusCode').should('eq', 200);
   facilityManage.verifyCoverImageModalClosed();
+  facilityManage.verifyCoverImageVisible();
   
   // Check: Delete the existing cover image
   facilityManage.clickCoverImage();
   facilityManage.clickDeleteCoverImage();
+  cy.wait('@deleteCoverImage').its('response.statusCode').should('eq', 200);
+  facilityManage.verifyCoverImageNotVisible();
 });

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

Comment on lines +52 to +54
afterEach(() => {
cy.saveLocalStorage();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add proper test cleanup

The test should clean up any resources it creates to maintain test isolation.

 afterEach(() => {
   cy.saveLocalStorage();
+  // Clean up any uploaded images to maintain test isolation
+  cy.get('@deleteCoverImage').then((interception) => {
+    if (interception) {
+      facilityManage.clickCoverImage();
+      facilityManage.clickDeleteCoverImage();
+      cy.wait('@deleteCoverImage');
+    }
+  });
 });

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

Comment on lines +19 to +27
beforeEach(() => {
cy.viewport(1280, 720);
cy.restoreLocalStorage();
cy.clearLocalStorage(/filters--.+/);
cy.awaitUrl("/");
facilityPage.typeFacilitySearch(facilityName);
facilityPage.verifyFacilityBadgeContent(facilityName);
facilityPage.visitAlreadyCreatedFacility();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Implement API intercepts as specified in PR objectives

The PR objectives mention using cy.intercept() for API verification, but these are missing in the implementation.

Add API intercepts before navigation:

 beforeEach(() => {
   cy.viewport(1280, 720);
   cy.restoreLocalStorage();
   cy.clearLocalStorage(/filters--.+/);
+  cy.intercept('GET', '/api/v1/facility/*').as('getFacility');
+  cy.intercept('POST', '/api/v1/facility/*/cover_image').as('uploadCoverImage');
+  cy.intercept('DELETE', '/api/v1/facility/*/cover_image').as('deleteCoverImage');
   cy.awaitUrl("/");
   facilityPage.typeFacilitySearch(facilityName);
   facilityPage.verifyFacilityBadgeContent(facilityName);
   facilityPage.visitAlreadyCreatedFacility();
+  cy.wait('@getFacility');
 });
📝 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
beforeEach(() => {
cy.viewport(1280, 720);
cy.restoreLocalStorage();
cy.clearLocalStorage(/filters--.+/);
cy.awaitUrl("/");
facilityPage.typeFacilitySearch(facilityName);
facilityPage.verifyFacilityBadgeContent(facilityName);
facilityPage.visitAlreadyCreatedFacility();
});
beforeEach(() => {
cy.viewport(1280, 720);
cy.restoreLocalStorage();
cy.clearLocalStorage(/filters--.+/);
cy.intercept('GET', '/api/v1/facility/*').as('getFacility');
cy.intercept('POST', '/api/v1/facility/*/cover_image').as('uploadCoverImage');
cy.intercept('DELETE', '/api/v1/facility/*/cover_image').as('deleteCoverImage');
cy.awaitUrl("/");
facilityPage.typeFacilitySearch(facilityName);
facilityPage.verifyFacilityBadgeContent(facilityName);
facilityPage.visitAlreadyCreatedFacility();
cy.wait('@getFacility');
});

Comment on lines +8 to +10
clickCancelButton() {
cy.get("#cancel").scrollIntoView().should("be.visible").click();
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use a more specific selector for the cancel button

The current selector '#cancel' is too generic and could match unintended elements on the page. Consider using a more specific selector that includes the context of the cover image modal.

-    cy.get("#cancel").scrollIntoView().should("be.visible").click();
+    cy.get("[data-testid='cover-image-modal-cancel']").scrollIntoView().should("be.visible").click();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
clickCancelButton() {
cy.get("#cancel").scrollIntoView().should("be.visible").click();
}
clickCancelButton() {
cy.get("[data-testid='cover-image-modal-cancel']").scrollIntoView().should("be.visible").click();
}

Comment on lines +12 to +14
verifyCoverImageModalClosed() {
cy.get("#upload-cover-image").should("not.exist");
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Verify modal closure using the modal container

The current implementation checks for the upload button's non-existence, which might not accurately represent whether the modal is closed. Consider checking the modal container element instead.

-    cy.get("#upload-cover-image").should("not.exist");
+    cy.get("[data-testid='cover-image-modal']").should("not.exist");

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

Comment on lines +27 to +30
cy.intercept("POST", "**/api/v1/facility/**").as("uploadCoverImage");
cy.get("#save-cover-image").scrollIntoView().click();
cy.wait("@uploadCoverImage").its("response.statusCode").should("eq", 200);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve API intercept and error handling

The current implementation has several areas for improvement:

  1. The API route wildcard could match unintended requests
  2. No handling of failed uploads
  3. Multiple responsibilities in a single method
-    cy.intercept("POST", "**/api/v1/facility/**").as("uploadCoverImage");
-    cy.get("#save-cover-image").scrollIntoView().click();
-    cy.wait("@uploadCoverImage").its("response.statusCode").should("eq", 200);
+    cy.intercept("POST", "**/api/v1/facility/*/cover_image").as("uploadCoverImage");
+    cy.get("#save-cover-image").scrollIntoView().should("be.visible").click();
+    cy.wait("@uploadCoverImage").then((interception) => {
+      if (interception.response?.statusCode !== 200) {
+        throw new Error(`Failed to upload cover image: ${interception.response?.statusCode}`);
+      }
+    });
📝 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.intercept("POST", "**/api/v1/facility/**").as("uploadCoverImage");
cy.get("#save-cover-image").scrollIntoView().click();
cy.wait("@uploadCoverImage").its("response.statusCode").should("eq", 200);
}
cy.intercept("POST", "**/api/v1/facility/*/cover_image").as("uploadCoverImage");
cy.get("#save-cover-image").scrollIntoView().should("be.visible").click();
cy.wait("@uploadCoverImage").then((interception) => {
if (interception.response?.statusCode !== 200) {
throw new Error(`Failed to upload cover image: ${interception.response?.statusCode}`);
}
});

Comment on lines +32 to +36
clickDeleteCoverImage() {
cy.intercept("DELETE", "**/api/v1/facility/**").as("deleteCoverImage");
cy.get("#delete-cover-image").scrollIntoView();
cy.get("#delete-cover-image").click();
cy.wait("@deleteCoverImage").its("response.statusCode").should("eq", 204);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix duplicate scrollIntoView and improve error handling

The current implementation has several issues:

  1. Duplicate scrollIntoView calls
  2. The API route wildcard could match unintended requests
  3. No handling of failed deletions
-    cy.intercept("DELETE", "**/api/v1/facility/**").as("deleteCoverImage");
-    cy.get("#delete-cover-image").scrollIntoView();
-    cy.get("#delete-cover-image").click();
-    cy.wait("@deleteCoverImage").its("response.statusCode").should("eq", 204);
+    cy.intercept("DELETE", "**/api/v1/facility/*/cover_image").as("deleteCoverImage");
+    cy.get("#delete-cover-image").scrollIntoView().should("be.visible").click();
+    cy.wait("@deleteCoverImage").then((interception) => {
+      if (interception.response?.statusCode !== 204) {
+        throw new Error(`Failed to delete cover image: ${interception.response?.statusCode}`);
+      }
+    });
📝 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
clickDeleteCoverImage() {
cy.intercept("DELETE", "**/api/v1/facility/**").as("deleteCoverImage");
cy.get("#delete-cover-image").scrollIntoView();
cy.get("#delete-cover-image").click();
cy.wait("@deleteCoverImage").its("response.statusCode").should("eq", 204);
clickDeleteCoverImage() {
cy.intercept("DELETE", "**/api/v1/facility/*/cover_image").as("deleteCoverImage");
cy.get("#delete-cover-image").scrollIntoView().should("be.visible").click();
cy.wait("@deleteCoverImage").then((interception) => {
if (interception.response?.statusCode !== 204) {
throw new Error(`Failed to delete cover image: ${interception.response?.statusCode}`);
}
});

@nihal467
Copy link
Member

nihal467 commented Nov 26, 2024

@rohitlingarker look into the code rabbit review,

  • As per issue, the API verification is not done once the file upload is completed [Also it was flag by the AI review]

image
image

  • Remove the manually hardcoded password usage in the test file. Using the existing login function, try to implement a solution where the password is dynamically allocated. The screenshot is a solution provided by ChatGPT to handle this kind of situation, though I wouldn't say it's well optimized. Think of a better solution that can scale and avoid hardcoded values.
  • remove the unused image you push to this PR " facility-cover-image1 "

@nihal467
Copy link
Member

nihal467 commented Dec 4, 2024

@rohitlingarker any update

@github-actions github-actions bot removed the stale label Dec 5, 2024
@nihal467
Copy link
Member

nihal467 commented Dec 9, 2024

@rohitlingarker Closing the PR due to inactivity and unassigning you from the issue. Feel free to reopen the PR and get reassigned if you are still working on it.

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.

Refactor the existing cypress test to upload cover image
3 participants