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

Add Test suit for Image Upload Functionality #9373

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Dec 11, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

  • Add specs that demonstrate bug / test a new feature.
  • Update product documentation.
  • Ensure that UI text is kept in I18n files.
  • Prep screenshot or demo video for changelog entry, and attach it to issue.
  • Request for Peer Reviews
  • Completion of QA

Summary by CodeRabbit

  • New Features

    • Introduced functionality to upload, edit, and delete cover images for facilities.
    • Added a delete button for avatar management in the AvatarEditModal component.
  • Bug Fixes

    • Improved accessibility by updating button IDs for better targeting in tests and styles.
  • Tests

    • Implemented a comprehensive end-to-end test suite for cover image functionalities.
  • Enhancements

    • Enhanced methods for managing facility capacities and network request verification in the FacilityManage class.

Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

This pull request introduces comprehensive Cypress end-to-end testing for facility cover image functionality. The changes span multiple files, including a new test specification for facility cover image upload, enhancements to the FacilityManage page object, and modifications to the AvatarEditModal component. The implementation focuses on testing cover image operations such as uploading, editing, and deleting across different user roles, with robust API request interception and verification.

Changes

File Change Summary
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts Added new E2E test suite for facility cover image functionality with role-based testing
cypress/pageobject/Facility/FacilityManage.ts Added multiple methods for cover image and facility capacity management, including request interception and verification methods
src/components/Common/AvatarEditModal.tsx Added delete button for cover image and updated existing save button with ID

Assessment against linked issues

Objective Addressed Explanation
Refactor Cypress test for cover image upload [#9109]
Follow Page Object Model (POM) structure
Verify API requests using cy.intercept()
Test workflows for District Admin
Test access verification with non-admin user

Possibly related PRs

Suggested labels

tested, reviewed

Suggested reviewers

  • nihal467
  • rithviknishad
  • Jacobjeevan

Poem

🐰 Hop, hop, through the code we go,
Cover images dancing to and fro,
Cypress tests, sharp and bright,
Uploading pixels with pure delight!
A rabbit's tale of digital grace 📸✨

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. We would love to hear your feedback on Discord.


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

netlify bot commented Dec 11, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit c9f89a6
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/676e3cfa60827c0008aec877
😎 Deploy Preview https://deploy-preview-9373--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.

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

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

@JavidSumra JavidSumra marked this pull request as ready for review December 13, 2024 12:18
@JavidSumra JavidSumra requested a review from a team as a code owner December 13, 2024 12:18
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 (1)
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1)

12-21: Consider expanding role coverage in test data.

While the current test data covers basic roles, consider adding more role variations (e.g., stateAdmin, facilityStaff) to ensure comprehensive testing of permissions and edge cases.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2611a32 and 437e68a.

⛔ Files ignored due to path filters (2)
  • cypress/fixtures/facility-cover-image-1.jpg is excluded by !**/*.jpg
  • cypress/fixtures/facility-cover-image.jpg is excluded by !**/*.jpg
📒 Files selected for processing (4)
  • cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1 hunks)
  • cypress/pageobject/Facility/FacilityManage.ts (2 hunks)
  • public/locale/en.json (2 hunks)
  • src/components/Common/AvatarEditModal.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • public/locale/en.json
🔇 Additional comments (5)
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (2)

1-10: LGTM! Well-structured imports and interface definition.

The imports are appropriate for the test requirements, and the interface provides good type safety for role validation.


36-43: 🛠️ Refactor suggestion

Add error handling for navigation failures.

The navigation step cy.awaitUrl("/") should include error handling to ensure the test fails gracefully if navigation fails.

-      cy.awaitUrl("/");
+      cy.awaitUrl("/").then((url) => {
+        if (!url.includes('/')) {
+          throw new Error('Navigation to home page failed');
+        }
+      });
⛔ Skipped due to learnings
Learnt from: Jacobjeevan
PR: ohcnetwork/care_fe#9145
File: cypress/e2e/facility_spec/FacilityCreation.cy.ts:177-180
Timestamp: 2024-11-18T10:44:30.303Z
Learning: In `cypress/e2e/facility_spec/FacilityCreation.cy.ts`, when testing bed and staff capacity individually for additional error verification, we prefer to use separate method calls to handle bed and staff capacity, rather than using `facilityPage.createNewFacility(testFacilityData)` which also handles bed management.
cypress/pageobject/Facility/FacilityManage.ts (1)

21-27: LGTM! Well-implemented UI interaction methods.

The click handler methods are well-implemented using the custom verifyAndClickElement helper.

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

Line range hint 285-291: LGTM! Well-implemented delete functionality.

The delete button implementation is clean and includes proper disabled state handling during processing.


Line range hint 1-1: Verify API endpoint consistency across the codebase.

Let's verify that the API endpoints used in the tests match the actual endpoints used in the application.

✅ Verification successful

Let me verify the HTTP methods used with these endpoints by checking the component implementation.


Let me check the actual implementation of the avatar/image upload functionality in the component.


API endpoint consistency verification completed

Based on the search results, the API endpoints for cover image operations are consistently defined and used across the codebase:

  • API definition in src/Utils/request/api.tsx: /api/v1/facility/{id}/cover_image/
  • Usage in src/components/Facility/FacilityHome.tsx: /api/v1/facility/${facilityId}/cover_image/
  • Test intercepts in cypress/pageobject/Facility/FacilityManage.ts match the pattern: /api/v1/facility/*/cover_image/

The HTTP methods are also consistent:

  • POST for upload (FacilityManage.ts)
  • DELETE for removal (api.tsx and FacilityManage.ts)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for API endpoint definitions and usage
rg -A 2 "api/v1/facility/.*/cover_image" --type ts

Length of output: 945


Script:

#!/bin/bash
# Search for the implementation in AvatarEditModal.tsx
rg -A 5 "cover_image" src/components/Common/AvatarEditModal.tsx

Length of output: 63


Script:

#!/bin/bash
# Search for upload-related code in AvatarEditModal
ast-grep --pattern 'const $_ = async ($$$) => {
  $$$
  upload$$$
  $$$
}'  src/components/Common/AvatarEditModal.tsx

Length of output: 118

cypress/e2e/facility_spec/FacilityCoverImage.cy.ts Outdated Show resolved Hide resolved
cypress/pageobject/Facility/FacilityManage.ts Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

12-21: Consider moving test data to fixtures.

While the test data structure is clear, hardcoded facility names could make tests brittle. Consider:

  1. Moving test data to a separate fixture file
  2. Using dynamic facility creation or a test data factory pattern

Example refactor:

// cypress/fixtures/facility-roles.json
{
  "rolesAndFacility": [
    {
      "role": "districtAdmin",
      "facilityName": "Dummy Facility 40"
    },
    {
      "role": "devDoctor",
      "facilityName": "Dummy Facility 4"
    }
  ]
}

// In test file
let rolesAndFacility: IRoleAndFacility[];

before(() => {
  cy.fixture('facility-roles.json').then((data) => {
    rolesAndFacility = data.rolesAndFacility;
  });
});

23-29: Consider extracting configuration values.

Move configuration values like viewport dimensions and notification text to a central configuration file or Cypress config for better maintainability.

Example:

// cypress/config/test-config.ts
export const VIEWPORT = {
  width: 1920,
  height: 1080
};

export const NOTIFICATIONS = {
  coverImageUpdate: "Cover image updated."
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 437e68a and a96452f.

📒 Files selected for processing (1)
  • cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1 hunks)
🔇 Additional comments (2)
cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (2)

1-10: LGTM! Well-structured imports and type definitions.

The imports are well-organized, and the interface definition uses TypeScript features effectively for type safety.


45-73: Add negative test cases and image validation tests.

The current test suite only covers happy paths.

cypress/e2e/facility_spec/FacilityCoverImage.cy.ts Outdated Show resolved Hide resolved
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 13, 2024
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Dec 15, 2024
Copy link

👋 Hi, @JavidSumra,
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 stale label Dec 23, 2024
@rithviknishad
Copy link
Member

Closing due to no activity

@JavidSumra
Copy link
Contributor Author

Hey @rithviknishad got some college work so due to that not able to contribute can you please open it again?

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 23, 2024
@sainak sainak reopened this Dec 23, 2024
@sainak sainak removed needs-triage question Further information is requested labels Dec 23, 2024
@JavidSumra
Copy link
Contributor Author

Hey @nihal467, I have a doubt regarding this test suite. Since the upload and edit cover image procedures use the same API call, can we replace the edit procedure test with a test for an invalid image width instead?

@github-actions github-actions bot added needs-triage question Further information is requested labels Dec 23, 2024
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Dec 23, 2024
@nihal467
Copy link
Member

Hey @nihal467, I have a doubt regarding this test suite. Since the upload and edit cover image procedures use the same API call, can we replace the edit procedure test with a test for an invalid image width instead?

You can do that: verify the error message, replace the existing image with a new one, and complete the test.

@github-actions github-actions bot removed the stale label Dec 24, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

111-131: 🛠️ Refactor suggestion

Enhance network request handling reliability.

The network request interception methods need improvements for better reliability and flexibility.

  1. Add timeouts to prevent test hanging:
   verifyImageUploadRequest(expectedCode: number = 200) {
-    cy.wait("@imageUploadReq")
+    cy.wait("@imageUploadReq", { timeout: 10000 })
       .its("response.statusCode")
       .should("eq", expectedCode);
   }

   verifyImageDeleteRequest() {
-    cy.wait("@imageDeleteReq").its("response.statusCode").should("eq", 204);
+    cy.wait("@imageDeleteReq", { timeout: 10000 })
+      .its("response.statusCode")
+      .should("eq", 204);
   }
  1. Add error handling for failed requests:
   verifyImageUploadRequest(expectedCode: number = 200) {
     cy.wait("@imageUploadReq", { timeout: 10000 })
-      .its("response.statusCode")
-      .should("eq", expectedCode);
+      .then((interception) => {
+        if (interception.error) {
+          throw new Error(`Request failed: ${interception.error}`);
+        }
+        expect(interception.response?.statusCode).to.equal(expectedCode);
+      });
   }
  1. Make the delete status code configurable like upload:
-  verifyImageDeleteRequest() {
+  verifyImageDeleteRequest(expectedCode: number = 204) {
     cy.wait("@imageDeleteReq", { timeout: 10000 })
       .its("response.statusCode")
-      .should("eq", 204);
+      .should("eq", expectedCode);
   }
🧹 Nitpick comments (1)
cypress/pageobject/Facility/FacilityManage.ts (1)

29-51: Add visibility checks for capacity-related elements.

The capacity management methods should verify element visibility before interaction to prevent flaky tests.

Consider adding visibility checks:

   verifyTotalDoctorCapacity(expectedCapacity: string) {
-    cy.get("#facility-doctor-totalcapacity").contains(expectedCapacity);
+    cy.get("#facility-doctor-totalcapacity")
+      .should('be.visible')
+      .contains(expectedCapacity);
   }

   clickEditFacilityDoctorCapacity() {
-    cy.get("#edit-facility-doctorcapacity").click();
+    cy.get("#edit-facility-doctorcapacity")
+      .should('be.visible')
+      .click();
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a96452f and 0dd104a.

📒 Files selected for processing (3)
  • cypress/e2e/facility_spec/FacilityCoverImage.cy.ts (1 hunks)
  • cypress/pageobject/Facility/FacilityManage.ts (2 hunks)
  • src/components/Common/AvatarEditModal.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/components/Common/AvatarEditModal.tsx
  • cypress/e2e/facility_spec/FacilityCoverImage.cy.ts
🔇 Additional comments (2)
cypress/pageobject/Facility/FacilityManage.ts (2)

21-27: LGTM! Well-structured cover image management methods.

The methods are concise, follow the page object pattern, and make good use of the custom helper for element verification.


101-109: LGTM! Well-implemented type management methods.

Good practice using scrollIntoView to ensure element visibility before interaction.

cypress/pageobject/Facility/FacilityManage.ts Show resolved Hide resolved
@rithviknishad rithviknishad added needs review and removed question Further information is requested needs-triage labels Dec 24, 2024
@rithviknishad
Copy link
Member

no longer relevant in new architecture

cc: @nihal467

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