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 Cypress Test Suite for Facility Notice Board Functionality Verification #9045

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

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 7, 2024

Proposed Changes

@ohcnetwork/care-fe-code-reviewers

Merge Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new test case for verifying notice board functionality in the facility homepage.
    • Added a FacilityNotify class to manage notifications, including methods for sending and verifying notifications.
  • Enhancements

    • Improved accessibility by adding id attributes to various components, including notification messages and sidebar items.
    • Updated input handling in the FacilityCard component for better data management.
  • Bug Fixes

    • Enhanced user session management with a new sign-out method in the login page.

@JavidSumra JavidSumra requested a review from a team as a code owner November 7, 2024 12:44
Copy link

coderabbitai bot commented Nov 7, 2024

Walkthrough

The pull request introduces enhancements to the Cypress end-to-end test suite for the facility homepage, specifically by adding a new test case for verifying notice board functionality. It incorporates new methods in the FacilityNotify class for managing notifications and modifies existing tests to improve their structure. Additionally, several components are updated to include new id attributes for accessibility. Overall, the changes aim to refine the testing process and improve interaction with the notification system.

Changes

Files Change Summary
cypress/e2e/facility_spec/FacilityHomepage.cy.ts Added a new test case for verifying notice board functionality, including various notification checks.
cypress/pageobject/Facility/FacilityNotify.ts Introduced FacilityNotify class with methods for handling notifications and intercepting API requests.
cypress/pageobject/Login/LoginPage.ts Added clickSignOutBtn method for user sign-out functionality.
src/components/Common/Sidebar/SidebarItem.tsx Added optional id property to SidebarItemBaseProps for enhanced flexibility.
src/components/Facility/FacilityCard.tsx Added id attribute to the facility name <span> in the notification modal.
src/components/Notifications/NoticeBoard.tsx Added id attribute to the notification message display <div>.
src/components/Notifications/NotificationsList.tsx Added id attributes to message display and notification button components for better accessibility.

Assessment against linked issues

Objective Addressed Explanation
Add a new Cypress test to verify the notice board functionality (#9041)
Use reusable functions from commands.ts and existing tests in the new Cypress test (#9041)
Implement necessary API verifications in the new test (#9041)
Remove verification of the notify button in existing tests (#9041)
Create a new file FacilityNotify.ts in the pageobject folder (#9041)

Possibly related PRs

Suggested labels

tested, good to merge

Suggested reviewers

  • rithviknishad

Poem

In the realm of tests, we hop and play,
New features sprout, brightening the day.
Notifications dance, with IDs in sight,
Cypress now gleams, all functions feel right.
So here’s to the code, both lively and spry,
A rabbit's delight, as we leap and fly! 🐇✨


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

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit dd38cef
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/672cc06392a41400082d9ffa
😎 Deploy Preview https://deploy-preview-9045--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 Deploy-Failed Deplyment is not showing preview label Nov 7, 2024
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (8)
cypress/pageobject/Login/LoginPage.ts (1)

38-40: Add JSDoc documentation for better maintainability.

The implementation looks good and aligns well with the existing code patterns. Consider adding JSDoc documentation to describe the method's purpose and behavior.

+  /**
+   * Clicks the sign-out button after verifying its presence
+   * @returns {void}
+   */
   clickSignOutBtn(): void {
     cy.verifyAndClickElement("#sign-out-button", "Sign Out");
   }
cypress/pageobject/Facility/FacilityNotify.ts (2)

2-4: Consider using data-testid for more reliable element selection.

The #NotifyModalMessageInput selector relies on an ID that might change. Using a dedicated data-testid attribute would make the test more maintainable.

-    cy.get("#NotifyModalMessageInput").should("be.visible").type(message);
+    cy.get('[data-testid="notify-modal-message-input"]').should("be.visible").type(message);

1-36: Add JSDoc documentation and improve class structure.

The class would benefit from proper documentation and a more organized structure.

+/**
+ * Page Object Model for facility notification functionality.
+ * Handles UI interactions and API verifications for the notification system.
+ */
 export class FacilityNotify {
+  // Add private constants
+  private readonly SELECTORS = {
+    NOTIFY_INPUT: '[data-testid="notify-modal-message-input"]',
+    NOTICE_BOARD_LINK: '[data-testid="notice-board-link"]',
+    NOTIFICATION_BTN: '[data-testid="notification-slide-btn"]'
+  } as const;
+
+  // Group methods by functionality
+  // UI Interactions
+  // API Interactions
 }
src/components/Common/Sidebar/SidebarItem.tsx (1)

35-35: Simplify id prop access.

The optional chaining operator (?.) is unnecessary here since TypeScript already handles the optional type. You can directly use props.id.

-        id={props?.id}
+        id={props.id}
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (2)

147-149: Move selectors to POM class.

The selectors like #notify-facility-name and .error-text should be moved to the FacilityNotify POM class for better maintainability.


160-162: Consider extracting login flow to a shared command.

The login sequence appears in multiple places. Consider creating a custom Cypress command for this common operation.

// commands.ts
Cypress.Commands.add('switchUser', (role: string) => {
  cy.get('@loginPage').then((loginPage) => {
    loginPage.ensureLoggedIn();
    loginPage.clickSignOutBtn();
    if (role === 'nurse') {
      loginPage.loginManuallyAsNurse();
    }
    // Add other roles as needed
  });
});

// Usage in test
cy.switchUser('nurse');
src/components/Facility/FacilityCard.tsx (2)

Line range hint 41-60: Consider enhancing notification handling.

The notification submission logic could benefit from the following improvements:

  1. Add a loading state during API call to prevent multiple submissions
  2. Implement character limit validation
  3. Consider rate limiting to prevent notification spam

Here's a suggested implementation:

 const [notifyMessage, setNotifyMessage] = useState("");
 const [notifyError, setNotifyError] = useState("");
+const [isSubmitting, setIsSubmitting] = useState(false);
+const MAX_MESSAGE_LENGTH = 500;

 const handleNotifySubmit = async (id: any) => {
-  if (notifyMessage.trim().length >= 1) {
+  if (isSubmitting) return;
+  
+  if (notifyMessage.trim().length === 0) {
+    setNotifyError("Message cannot be empty");
+    return;
+  }
+
+  if (notifyMessage.length > MAX_MESSAGE_LENGTH) {
+    setNotifyError(`Message cannot exceed ${MAX_MESSAGE_LENGTH} characters`);
+    return;
+  }
+
+  try {
+    setIsSubmitting(true);
     setNotifyError("");
     const { res } = await request(routes.sendNotificationMessages, {
       body: {
         facility: id,
         message: notifyMessage,
       },
     });
     if (res?.ok) {
       Notification.Success({
         msg: "Facility Notified",
       });
       setNotifyMessage("");
       setNotifyModalFor(undefined);
     } else {
       Notification.Error({ msg: "Something went wrong..." });
     }
-  } else {
-    setNotifyError("Message cannot be empty");
+  } finally {
+    setIsSubmitting(false);
   }
 };

TextAreaFormField onChange handler is incompatible with component implementation

The component implementation shows that TextAreaFormField internally uses e.target.value in its onChange handler, but the usage in FacilityCard.tsx uses e.value. This will cause the text area to not update properly.

The correct usage should be:

onChange={(e) => setNotifyMessage(e.target.value)}
🔗 Analysis chain

Line range hint 188-224: Verify TextAreaFormField onChange handler compatibility.

The onChange handler now uses e.value instead of the standard e.target.value. This suggests a change in the TextAreaFormField component's event handling.

Let's verify the TextAreaFormField component's interface:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for TextAreaFormField component definition and usage
echo "Searching for TextAreaFormField component definition..."
ast-grep --pattern 'export $_ TextAreaFormField = $_'

echo -e "\nSearching for other TextAreaFormField onChange handlers..."
rg "TextAreaFormField.*onChange" --type typescript --type typescriptreact

Length of output: 420


Script:

#!/bin/bash
# Let's try different approaches to find the component and its usage

# Find files containing TextAreaFormField
echo "Files containing TextAreaFormField:"
rg -l "TextAreaFormField"

# Search for onChange handlers in those files
echo -e "\nTextAreaFormField onChange usage:"
rg -B2 -A2 "TextAreaFormField.*onChange"

# Look for the component definition
echo -e "\nTextAreaFormField component definition:"
rg -B5 -A10 "export.*TextAreaFormField"

Length of output: 3602


Script:

#!/bin/bash
# Let's look at the TextAreaFormField component implementation
echo "TextAreaFormField component implementation:"
cat src/components/Form/FormFields/TextAreaFormField.tsx

# Also search for its actual usage patterns
echo -e "\nTextAreaFormField usage with onChange:"
rg -B2 -A2 "<TextAreaFormField.*onChange" --type tsx

Length of output: 1838

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c27f595 and 66d6ef4.

📒 Files selected for processing (7)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/pageobject/Facility/FacilityNotify.ts (1 hunks)
  • cypress/pageobject/Login/LoginPage.ts (1 hunks)
  • src/components/Common/Sidebar/SidebarItem.tsx (2 hunks)
  • src/components/Facility/FacilityCard.tsx (1 hunks)
  • src/components/Notifications/NoticeBoard.tsx (1 hunks)
  • src/components/Notifications/NotificationsList.tsx (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/components/Notifications/NoticeBoard.tsx
🧰 Additional context used
🪛 GitHub Check: cypress-run (4)
src/components/Notifications/NotificationsList.tsx

[failure] 479-479:
Type '{ text: string; id: string; do: () => void; icon: Element; badgeCount: number; handleOverflow: any; }' is not assignable to type 'IntrinsicAttributes & ((Omit<{ ref?: Ref | undefined; text: string; icon: ReactNode; onItemClick?: (() => void) | undefined; external?: true | undefined; badgeCount?: number | undefined; selected?: boolean | undefined; handleOverflow?: any; } & { ...; }, "ref"> | Omit<...>) & RefAttributes<...>)'.

🪛 GitHub Check: cypress-run (3)
src/components/Notifications/NotificationsList.tsx

[failure] 479-479:
Type '{ text: string; id: string; do: () => void; icon: Element; badgeCount: number; handleOverflow: any; }' is not assignable to type 'IntrinsicAttributes & ((Omit<{ ref?: Ref | undefined; text: string; icon: ReactNode; onItemClick?: (() => void) | undefined; external?: true | undefined; badgeCount?: number | undefined; selected?: boolean | undefined; handleOverflow?: any; } & { ...; }, "ref"> | Omit<...>) & RefAttributes<...>)'.

🪛 GitHub Check: cypress-run (2)
src/components/Notifications/NotificationsList.tsx

[failure] 479-479:
Type '{ text: string; id: string; do: () => void; icon: Element; badgeCount: number; handleOverflow: any; }' is not assignable to type 'IntrinsicAttributes & ((Omit<{ ref?: Ref | undefined; text: string; icon: ReactNode; onItemClick?: (() => void) | undefined; external?: true | undefined; badgeCount?: number | undefined; selected?: boolean | undefined; handleOverflow?: any; } & { ...; }, "ref"> | Omit<...>) & RefAttributes<...>)'.

🪛 GitHub Check: cypress-run (1)
src/components/Notifications/NotificationsList.tsx

[failure] 479-479:
Type '{ text: string; id: string; do: () => void; icon: Element; badgeCount: number; handleOverflow: any; }' is not assignable to type 'IntrinsicAttributes & ((Omit<{ ref?: Ref | undefined; text: string; icon: ReactNode; onItemClick?: (() => void) | undefined; external?: true | undefined; badgeCount?: number | undefined; selected?: boolean | undefined; handleOverflow?: any; } & { ...; }, "ref"> | Omit<...>) & RefAttributes<...>)'.

🔇 Additional comments (6)
cypress/pageobject/Facility/FacilityNotify.ts (1)

1-36: Verify integration with existing test commands.

The PR objectives mention using reusable functions from commands.ts. Let's verify this integration.

src/components/Common/Sidebar/SidebarItem.tsx (2)

24-24: LGTM! Type definition properly supports testing requirements.

The addition of the optional id prop enhances component testability while maintaining backward compatibility.


Line range hint 43-47: Verify resetHistory behavior in notification flow.

There's a comment suggesting uncertainty about resetHistory. Since this component is used in the notification system, we should verify that resetting history doesn't interfere with the notification flow, especially for the Facility Notice Board functionality.

✅ Verification successful

resetHistory usage is correct and safe for notifications

The resetHistory implementation is working as intended:

  • It's properly imported from useAppHistory hook
  • It's used correctly in the click handler sequence
  • The implementation in HistoryAPIProvider shows it only resets to the first history entry
  • The notification flow in NotificationsList uses SidebarItem as a navigation component, where resetting history on click is the expected behavior

The comment can be safely removed as the implementation has been verified.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of resetHistory to understand its impact
echo "Searching for resetHistory usage patterns..."
rg -A 3 "resetHistory" --type ts --type tsx

# Search for notification-related components using this sidebar item
echo "Checking notification-related component usage..."
rg -A 5 "SidebarItem|ShrinkedSidebarItem" --type ts --type tsx | rg -i "notif|notice"

Length of output: 393


Script:

#!/bin/bash
# Search for resetHistory without file type restrictions
echo "Searching for resetHistory usage patterns..."
rg -A 3 "resetHistory"

# Search for SidebarItem usage in notification contexts
echo "Checking notification-related component usage..."
rg -A 5 "SidebarItem" | rg -i "notif|notice"

# Check the actual implementation in SidebarItem.tsx
echo "Checking SidebarItem implementation..."
cat src/components/Common/Sidebar/SidebarItem.tsx

Length of output: 6690

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

2-3: LGTM: Import and initialization changes follow POM pattern.

The new imports and instance initialization for FacilityNotify are properly structured following the Page Object Model pattern.

Also applies to: 5-6, 13-13


140-142: LGTM: Proper API verification pattern.

Good use of the intercept-action-verify pattern for API calls, ensuring reliable test execution.

Also applies to: 155-158, 164-166, 168-170

src/components/Facility/FacilityCard.tsx (1)

188-191: LGTM! Good addition of test id.

The addition of id="notify-facility-name" improves test stability and component accessibility.

Comment on lines +6 to +8
visitNoticeBoard(): void {
cy.get("a[href='/notice_board']").should("be.visible").click();
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add timeout and error handling for link interaction.

The notice board link interaction could be more robust with proper timeout and error handling.

-    cy.get("a[href='/notice_board']").should("be.visible").click();
+    cy.get('[data-testid="notice-board-link"]', { timeout: 10000 })
+      .should("be.visible")
+      .should("not.be.disabled")
+      .click();

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

Comment on lines +21 to +27
interceptPostNotificationReq(): void {
cy.intercept("POST", "**/api/v1/notification/notify").as("notifyFacility");
}

verifyPostNotificationReq(): void {
cy.wait("@notifyFacility").its("response.statusCode").should("eq", 204);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for notification POST requests.

The notification POST verification should handle error cases and validate request payload.

   interceptPostNotificationReq(): void {
-    cy.intercept("POST", "**/api/v1/notification/notify").as("notifyFacility");
+    cy.intercept("POST", this.API_PATHS.NOTIFICATION + '/notify').as("notifyFacility");
   }

   verifyPostNotificationReq(): void {
-    cy.wait("@notifyFacility").its("response.statusCode").should("eq", 204);
+    cy.wait("@notifyFacility").then((interception) => {
+      // Verify request payload
+      expect(interception.request.body).to.have.property('message');
+      // Verify response
+      expect(interception.response?.statusCode).to.equal(204);
+      // Handle potential error responses
+      if (interception.response?.statusCode !== 204) {
+        throw new Error(`Notification failed: ${interception.response?.body}`);
+      }
+    });
   }

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

Comment on lines +14 to +19
interceptFacilitySearchReq(): void {
cy.intercept("GET", "**/api/v1/facility/**").as("searchFacility");
}
verifyFacilitySearchReq(): void {
cy.wait("@searchFacility").its("response.statusCode").should("eq", 200);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve API interception configuration and type safety.

The facility search API interception could be more specific and type-safe.

+  private readonly API_PATHS = {
+    FACILITY_SEARCH: '**/api/v1/facility',
+    NOTIFICATION: '**/api/v1/notification'
+  } as const;
+
+  interface FacilitySearchResponse {
+    // Add expected response type definition
+    data: Array<{ id: string; name: string }>;
+  }
+
   interceptFacilitySearchReq(): void {
-    cy.intercept("GET", "**/api/v1/facility/**").as("searchFacility");
+    cy.intercept("GET", this.API_PATHS.FACILITY_SEARCH + '/**').as("searchFacility");
   }
   
   verifyFacilitySearchReq(): void {
-    cy.wait("@searchFacility").its("response.statusCode").should("eq", 200);
+    cy.wait("@searchFacility").then((interception) => {
+      expect(interception.response?.statusCode).to.equal(200);
+      expect(interception.response?.body).to.have.property('data');
+    });
   }

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

Comment on lines 138 to 172
it("Verify Notice Board Functionality", () => {
// search facility and verify it's loaded or not
facilityNotify.interceptFacilitySearchReq();
manageUserPage.typeFacilitySearch(facilityName);
facilityNotify.verifyFacilitySearchReq();
// verify facility name and notify button and click it
manageUserPage.assertFacilityInCard(facilityName);
facilityHome.clickFacilityNotifyButton();
// check visiblity of pop-up and frontend error on empty message
cy.verifyContentPresence("#notify-facility-name", [facilityName]);
cy.submitButton("Notify");
cy.verifyContentPresence(".error-text", [notificationErrorMsg]);
// close pop-up and verify
facilityHome.verifyAndCloseNotifyModal();
// send notification
facilityHome.clickFacilityNotifyButton();
facilityNotify.fillNotifyText(noitificationMessage);
facilityNotify.interceptPostNotificationReq();
cy.submitButton("Notify");
cy.verifyNotification("Facility Notified");
facilityNotify.verifyPostNotificationReq();
// signout as district admin and login as a Nurse
loginPage.ensureLoggedIn();
loginPage.clickSignOutBtn();
loginPage.loginManuallyAsNurse();
// Visit Notification Sidebar
facilityNotify.interceptGetNotificationReq();
facilityNotify.visitNoticeBoard();
facilityNotify.verifyGetNotificationReq();
cy.verifyContentPresence("#notification-message", [noitificationMessage]);
facilityNotify.interceptGetNotificationReq();
cy.verifyAndClickElement("#notification-slide-btn", "Notifications");
facilityNotify.verifyGetNotificationReq();
cy.verifyContentPresence("#notification-slide-msg", [noitificationMessage]);
});
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding negative test cases and cleanup.

The test covers the happy path well but could be enhanced with:

  1. Negative test cases:
    • Network failure scenarios
    • Server error responses
    • Invalid message formats
  2. Test data cleanup after test execution
  3. Explicit assertions for state changes

Would you like me to provide example code for these scenarios?

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

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

138-172: Enhance test robustness with additional scenarios.

Consider adding the following test cases:

  1. Network failure scenarios:
it("handles network failure when sending notification", () => {
  // ... setup test
  facilityNotify.interceptPostNotificationReq().networkError();
  cy.submitButton("Notify");
  cy.verifyNotification("Failed to send notification");
});
  1. API error responses:
it("handles server error when sending notification", () => {
  // ... setup test
  facilityNotify.interceptPostNotificationReq().reply(500);
  cy.submitButton("Notify");
  cy.verifyNotification("Server error occurred");
});
  1. Consider extracting repeated steps into custom commands:
// commands.ts
Cypress.Commands.add('sendNotification', (facility, message) => {
  // ... reusable notification steps
});

Would you like me to provide more detailed examples for these scenarios?


146-149: Extract UI text selectors and messages as constants.

Consider extracting hardcoded selectors and messages into constants for better maintainability:

const SELECTORS = {
  facilityName: '#notify-facility-name',
  errorText: '.error-text',
  submitButton: 'Notify',
  successMessage: 'Facility Notified'
};

Also applies to: 156-157

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1566910 and dd38cef.

📒 Files selected for processing (2)
  • cypress/e2e/facility_spec/FacilityHomepage.cy.ts (3 hunks)
  • cypress/pageobject/Facility/FacilityNotify.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/pageobject/Facility/FacilityNotify.ts
🔇 Additional comments (2)
cypress/e2e/facility_spec/FacilityHomepage.cy.ts (2)

2-6: LGTM! Imports and instance creation follow POM pattern.

The new imports and instance creation for FacilityNotify align well with the existing Page Object Model structure.

Also applies to: 13-13


138-172: LGTM! Well-structured test implementation.

The test case effectively covers the notice board workflow with proper API verifications and UI assertions.

Comment on lines +27 to +29
const notificationErrorMsg = "Message cannot be empty";
const noitificationMessage =
"Reminder: The monthly report submission deadline is on 15th Nov. Ensure all entries are updated.";
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Move notification messages to i18n configuration.

As per PR objectives, UI text should support internationalization. Consider moving these message constants to the i18n configuration:

  • notificationErrorMsg
  • noitificationMessage

Example structure:

// i18n/en/notification.json
{
  "errors": {
    "emptyMessage": "Message cannot be empty"
  },
  "templates": {
    "monthlyReport": "Reminder: The monthly report submission deadline is on 15th Nov. Ensure all entries are updated."
  }
}

@nihal467
Copy link
Member

nihal467 commented Nov 7, 2024

@JavidSumra your test is failing on actions

@JavidSumra
Copy link
Contributor Author

Yup but it's passing on the local environment can you please provide images of that if possible @nihal467

@nihal467
Copy link
Member

nihal467 commented Nov 7, 2024

image

  • its failing in my local, recheck your PR

@JavidSumra
Copy link
Contributor Author

Ok sorry I'll check it again.

@JavidSumra
Copy link
Contributor Author

Hey @nihal467 as you can see below all test cases are passing in my local environment can you please guide me what should I do next?
image
if possible can you please provide a video or failure point?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Deploy-Failed Deplyment is not showing preview
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add New Cypress Test for Verifying Notice Board Functionality
2 participants