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

Refactor Cypress Auth Test to POM and Improve Test Stability #9024

Conversation

JavidSumra
Copy link
Contributor

@JavidSumra JavidSumra commented Nov 6, 2024

Proposed Changes

  • Fixes Refactor the Existing Cypress Auth Test #9015
  • Renamed auth_spec to homepage_spec and auth.cy.ts to UserLogin.cy.ts.
  • Merged auth.cy.ts and forgotpassword.cy.ts into UserLogin.cy.ts, organizing them under separate describe blocks.
  • Refactored test to use the Page Object Model (POM) approach, utilizing LoginPage.ts for login credentials.
  • Added API verification with cy.intercept before accessing #user-profile-name to ensure page load.
  • Converted hardcoded elements and actions to reusable functions in UserProfilePage.ts and commands.ts.
  • Removed hardcoded waits and replaced them with cy.intercept for stability.

Merge Checklist

  • Add specs that demonstrate bug fixes and verify new POM structure.
  • Update product documentation as needed.
  • Ensure all UI text updates are included in I18n files.
  • Prepare and attach a screenshot or demo video for changelog entry.
  • Request peer reviews from @ohcnetwork/care-fe-code-reviewers.
  • Complete QA and confirm test stability.

Summary by CodeRabbit

  • New Features

    • Introduced automated tests for user login and password recovery functionalities.
    • Enhanced login functionality with new methods for user interaction and request verification.
  • Bug Fixes

    • Removed outdated test files for "Forgot Password" and authorization functionalities.
  • Chores

    • Improved accessibility by adding identifiable attributes to buttons in the login and password recovery forms.

@JavidSumra JavidSumra requested a review from a team as a code owner November 6, 2024 13:20
Copy link
Contributor

coderabbitai bot commented Nov 6, 2024

Walkthrough

The changes involve the removal of two Cypress test files, ForgotPassword.cy.ts and auth.cy.ts, which contained tests for the "Forgot Password" and authentication functionalities, respectively. A new test file, UserLogin.cy.ts, has been introduced to consolidate and refactor the existing tests using the Page Object Model (POM) approach. Additionally, modifications were made to the LoginPage.ts class to enhance its functionality, and new IDs were added to the Login.tsx component to improve accessibility.

Changes

File Path Change Summary
cypress/e2e/auth_spec/ForgotPassword.cy.ts File deleted; contained tests for "Forgot Password" functionality.
cypress/e2e/auth_spec/auth.cy.ts File deleted; contained tests for authentication functionalities.
cypress/e2e/homepage_spec/UserLogin.cy.ts New file added; consolidates and refactors tests for user login and password recovery using POM.
cypress/pageobject/Login/LoginPage.ts Updated methods for enhanced functionality; added new methods for handling login and password recovery interactions.
src/components/Auth/Login.tsx Added new IDs for buttons and headings to improve accessibility; no changes to existing logic or validation processes.

Assessment against linked issues

Objective Addressed Explanation
Refactor existing auth tests to POM approach (9015)
Rename and merge test files into UserLogin.cy.ts (9015)
Add API verification and remove hardcoded waits (9015)
Combine tests for forgot password and login into one test (9015)

Possibly related PRs

Suggested labels

tested

Suggested reviewers

  • rithviknishad

Poem

In the land of code where rabbits play,
We’ve tidied up tests in a clever way.
With pages and buttons all in their place,
Login and reset now run with grace.
Hopping through functions, we cheer with delight,
For a smoother experience, oh what a sight! 🐇✨

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

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/homepage_spec/UserLogin.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 6, 2024

Deploy Preview for care-ohc ready!

Name Link
🔨 Latest commit 4caf7c1
🔍 Latest deploy log https://app.netlify.com/sites/care-ohc/deploys/673252a52e2a8a00088b78f9
😎 Deploy Preview https://deploy-preview-9024--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 6, 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: 3

🧹 Outside diff range and nitpick comments (7)
cypress/e2e/homepage_spec/UserLogin.cy.ts (2)

1-2: Add TypeScript type annotations for better maintainability.

While the code follows POM best practices, adding type annotations would improve maintainability and IDE support.

-import LoginPage from "pageobject/Login/LoginPage";
-const loginPage = new LoginPage();
+import { LoginPage } from "pageobject/Login/LoginPage";
+const loginPage: LoginPage = new LoginPage();

1-45: Consider adding test cases for edge scenarios.

The test suite has good basic coverage, but consider adding these scenarios:

  1. Session timeout handling
  2. Network error scenarios
  3. Concurrent login attempts
  4. Browser refresh during login process
  5. Password complexity validation

Also, consider creating custom commands for common assertions to improve code reuse.

Would you like me to help create these additional test cases or custom commands?

cypress/pageobject/Login/LoginPage.ts (4)

16-23: LGTM! Consider adding type safety for credentials.

Good implementation of parameterized login for both successful and failed scenarios. The boolean parameter effectively controls the test flow.

Consider creating an interface for credentials to make the code more maintainable:

interface LoginCredentials {
  username: string;
  password: string;
}

const VALID_CREDENTIALS: LoginCredentials = {
  username: "devdistrictadmin",
  password: "Coronasafe@123"
};

const INVALID_CREDENTIALS: LoginCredentials = {
  username: "devdistrictadmin",
  password: "Corona"
};

42-44: Consider adding API verification for sign out.

Good implementation using the helper function. However, consider adding API interception to verify the sign-out request completes successfully.

Add API verification similar to other methods:

interceptSignOutReq(): void {
  cy.intercept("POST", "**/api/v1/auth/logout").as("signOut");
}

verifySignOutReq(): void {
  cy.wait("@signOut").its("response.statusCode").should("eq", 200);
}

62-84: Consider parameterizing expected status codes.

Good implementation of API interception and verification. However, the expected status codes could be parameterized for more flexible testing.

Consider this approach:

interface ApiVerification {
  alias: string;
  expectedStatus: number;
}

verifyApiResponse({ alias, expectedStatus }: ApiVerification): void {
  cy.wait(`@${alias}`).its("response.statusCode").should("eq", expectedStatus);
}

This would allow more flexible status code verification while reducing code duplication.


Stability improvements need attention - hardcoded waits found

Multiple files still contain hardcoded waits that should be replaced with proper API interceptions and assertions:

  • PatientLogupdate.ts: Contains 5 instances of hardcoded waits (2000-3000ms)
  • PatientFileupload.ts: Contains 3 instances including a 5000ms wait
  • UsersManage.cy.ts: Contains 3 instances of 5000ms waits
  • PatientConsultation.ts: Contains waits of 5000ms and 3000ms
  • PatientRegistration.cy.ts: Contains 6 instances of hardcoded waits

While API interceptions are well implemented in the LoginPage and other files, the presence of numerous hardcoded waits indicates that the stability improvements are incomplete. These should be replaced with proper API interceptions and assertions for better test reliability.

🔗 Analysis chain

Line range hint 1-84: Verify test stability improvements.

The changes align well with the PR objectives, implementing POM pattern and improving stability through API verification. Let's verify the stability improvements:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining hardcoded waits in test files
echo "Checking for hardcoded waits..."
rg "cy\.wait\(\d+" cypress/

# Check for consistent use of API interception
echo "Checking API interception usage..."
rg "cy\.intercept" cypress/

Length of output: 9813

src/components/Auth/Login.tsx (1)

Line range hint 26-427: Consider splitting the component for better maintainability.

The component currently handles both login and forgot password flows. Consider splitting it into separate components:

  • LoginForm.tsx: Handle login flow
  • ForgotPasswordForm.tsx: Handle password recovery flow
  • AuthLayout.tsx: Handle common layout elements

This would improve:

  • Code maintainability
  • Component testing
  • Reusability
  • Separation of concerns

Additionally, consider extracting form validation logic into a custom hook for reusability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bbcfef0 and 7315053.

📒 Files selected for processing (5)
  • cypress/e2e/auth_spec/ForgotPassword.cy.ts (0 hunks)
  • cypress/e2e/auth_spec/auth.cy.ts (0 hunks)
  • cypress/e2e/homepage_spec/UserLogin.cy.ts (1 hunks)
  • cypress/pageobject/Login/LoginPage.ts (2 hunks)
  • src/components/Auth/Login.tsx (3 hunks)
💤 Files with no reviewable changes (2)
  • cypress/e2e/auth_spec/ForgotPassword.cy.ts
  • cypress/e2e/auth_spec/auth.cy.ts
🔇 Additional comments (4)
cypress/pageobject/Login/LoginPage.ts (1)

29-29: LGTM! Consistent use of submitButton command.

The change aligns with other login methods and improves test stability.

src/components/Auth/Login.tsx (3)

339-339: LGTM: Semantic ID for forgot password button.

The added ID follows clear naming conventions and supports the test automation objectives.


375-375: LGTM: Clear ID for navigation button.

The ID addition maintains consistency with the naming pattern and clearly indicates the button's purpose.


409-409: LGTM: Descriptive ID for form submission button.

The ID addition completes the set of button identifiers needed for test automation while maintaining naming consistency.

cypress/e2e/homepage_spec/UserLogin.cy.ts Outdated Show resolved Hide resolved
cypress/e2e/homepage_spec/UserLogin.cy.ts Outdated Show resolved Hide resolved
cypress/pageobject/Login/LoginPage.ts Show resolved Hide resolved
@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 6, 2024
@github-actions github-actions bot added the Deploy-Failed Deplyment is not showing preview label Nov 7, 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

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

16-23: Consider externalizing test credentials.

While the implementation is good, consider moving the hardcoded credentials to a configuration file or environment variables for better maintainability and security.

Example structure:

// cypress/fixtures/credentials.json
{
  "districtAdmin": {
    "username": "devdistrictadmin",
    "password": "Coronasafe@123",
    "invalidPassword": "Corona"
  }
}

42-60: Enable method chaining for better test flow.

Consider returning this from void methods to enable method chaining, which can make tests more readable and fluent.

Example refactor:

-  clickSignOutBtn(): void {
+  clickSignOutBtn(): this {
     cy.verifyAndClickElement("#sign-out-button", "Sign Out");
+    return this;
   }

-  fillUserNameInForgotPasswordForm(userName: string): void {
+  fillUserNameInForgotPasswordForm(userName: string): this {
     cy.get("#forgot_username").type(userName);
+    return this;
   }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7315053 and 1960971.

📒 Files selected for processing (2)
  • cypress/pageobject/Login/LoginPage.ts (2 hunks)
  • src/components/Auth/Login.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Auth/Login.tsx

cypress/pageobject/Login/LoginPage.ts Show resolved Hide resolved
@JavidSumra
Copy link
Contributor Author

Hey @nihal467 can you please review this PR

@rithviknishad rithviknishad removed the Deploy-Failed Deplyment is not showing preview label Nov 8, 2024
@github-actions github-actions bot added the merge conflict pull requests with merge conflict label Nov 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.

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

🧹 Outside diff range and nitpick comments (1)
.env (1)

10-11: Consider using separate environment files for different environments.

Instead of commenting out the production URL, consider:

  1. Using .env.development for local development
  2. Using .env.test for test environment
  3. Using .env.production for production

This helps prevent accidental commits of development configurations to production.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1960971 and a5145b2.

📒 Files selected for processing (2)
  • .env (1 hunks)
  • cypress/e2e/homepage_spec/UserLogin.cy.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • cypress/e2e/homepage_spec/UserLogin.cy.ts

.env Outdated Show resolved Hide resolved
@github-actions github-actions bot removed the merge conflict pull requests with merge conflict label Nov 11, 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: 4

🧹 Outside diff range and nitpick comments (6)
cypress/e2e/homepage_spec/UserLogin.cy.ts (1)

21-27: Enhance error case validation.

Add more comprehensive validation for the error scenario:

  1. Verify error message visibility
  2. Validate form state after error
-  it("Display an error when logging in as admin with incorrect password", () => {
+  it("should display appropriate error message for invalid credentials", { retries: 2 }, () => {
     loginPage.interceptLoginReq();
     loginPage.loginManuallyAsDistrictAdmin(false);
     loginPage.verifyLoginReq();
     cy.verifyNotification("No active account found with the given credentials");
+    // Verify form state after error
+    cy.get('input[name="password"]').should('have.class', 'error');
+    cy.get('button[type="submit"]').should('be.enabled');
     cy.closeNotification();
   });
cypress/pageobject/Login/LoginPage.ts (5)

16-23: Consider externalizing test credentials

While the conditional logic for handling correct/incorrect credentials is good, having hardcoded credentials in the test code could make maintenance difficult. Consider moving these to environment variables or a test configuration file.

// config/test-credentials.ts
export const TEST_CREDENTIALS = {
  districtAdmin: {
    username: 'devdistrictadmin',
    validPassword: 'Coronasafe@123',
    invalidPassword: 'Corona'
  }
};

// LoginPage.ts
import { TEST_CREDENTIALS } from '../config/test-credentials';

loginManuallyAsDistrictAdmin(isCorrectCredentials: boolean = true): void {
  const { username, validPassword, invalidPassword } = TEST_CREDENTIALS.districtAdmin;
  cy.get("input[id='username']").type(username);
  cy.get("input[id='password']").type(isCorrectCredentials ? validPassword : invalidPassword);
  cy.submitButton("Login");
}

46-52: Consider centralizing selectors

The methods are well-structured, but consider centralizing the selector strings to make maintenance easier and prevent duplication.

// Constants at the top of the file
private readonly SELECTORS = {
  forgotUsername: '#forgot_username',
  resetLinkBtn: '#send-reset-link-btn'
} as const;

// Updated methods
fillUserNameInForgotPasswordForm(userName: string): void {
  cy.get(this.SELECTORS.forgotUsername).type(userName);
}

clickSendResetLinkBtn(): void {
  cy.verifyAndClickElement(this.SELECTORS.resetLinkBtn, "Send Reset Link");
}

62-64: Add type safety for button text

Consider using an enum or union type for the button text parameter to prevent errors from typos or invalid text.

type ForgotPasswordText = 'Forgot Password?' | 'Reset Password';

clickForgotPasswordButton(text: ForgotPasswordText): void {
  cy.verifyAndClickElement("#forgot-pass-btn", text);
}

90-96: Enhance UI verification methods flexibility

Consider these improvements for better type safety and flexibility:

  1. Add type safety for the text array
  2. Allow custom selectors for different scenarios
type HeadingText = 'Forgot Password' | 'Reset Password' | 'Password Reset Instructions';

interface VerificationSelectors {
  loginButton?: string;
  forgotPasswordHeading?: string;
}

private readonly DEFAULT_SELECTORS: VerificationSelectors = {
  loginButton: '#login-button',
  forgotPasswordHeading: '#forgot-password-heading'
};

verifyLoginButtonPresence(selector?: string): void {
  cy.verifyContentPresence(selector ?? this.DEFAULT_SELECTORS.loginButton, ["Login"]);
}

verifyForgotPasswordHeading(text: HeadingText[], selector?: string): void {
  cy.verifyContentPresence(selector ?? this.DEFAULT_SELECTORS.forgotPasswordHeading, text);
}

Line range hint 1-99: Consider splitting the class for better separation of concerns

The LoginPage class currently handles multiple responsibilities:

  • Login functionality
  • Password reset functionality
  • API interceptions
  • UI verifications

Consider splitting this into smaller, more focused classes following the Single Responsibility Principle:

  • LoginPage - core login functionality
  • PasswordResetPage - password reset functionality
  • ApiInterceptor - API interception utilities
  • UIVerifier - UI verification utilities

Example structure:

// ApiInterceptor.ts
class ApiInterceptor {
  interceptLoginReq(): void { /* ... */ }
  verifyLoginReq(): void { /* ... */ }
  // ... other API methods
}

// PasswordResetPage.ts
class PasswordResetPage {
  fillUserNameInForgotPasswordForm(): void { /* ... */ }
  clickSendResetLinkBtn(): void { /* ... */ }
  // ... other password reset methods
}

// LoginPage.ts
class LoginPage {
  private api: ApiInterceptor;
  private passwordReset: PasswordResetPage;

  constructor() {
    this.api = new ApiInterceptor();
    this.passwordReset = new PasswordResetPage();
  }

  // ... core login methods
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a5145b2 and 4caf7c1.

📒 Files selected for processing (3)
  • cypress/e2e/homepage_spec/UserLogin.cy.ts (1 hunks)
  • cypress/pageobject/Login/LoginPage.ts (2 hunks)
  • src/components/Auth/Login.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/Auth/Login.tsx
🔇 Additional comments (1)
cypress/pageobject/Login/LoginPage.ts (1)

29-29: LGTM!

The change to use cy.submitButton is consistent with other login methods and improves maintainability.

Comment on lines +1 to +5
import LoginPage from "pageobject/Login/LoginPage";

const loginPage = new LoginPage();
const userName = "dummy_user_1";
const forgotPasswordHeading = "Forgot password?";
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

Move test data to fixtures and improve constant scoping.

Consider these improvements:

  1. Move test data to a fixture file for better maintainability
  2. Move constants inside the relevant describe blocks where they are used
 import LoginPage from "pageobject/Login/LoginPage";

 const loginPage = new LoginPage();
-const userName = "dummy_user_1";
-const forgotPasswordHeading = "Forgot password?";

+// Move to cypress/fixtures/auth.json
+{
+  "testUsers": {
+    "dummy_user_1": {
+      "username": "dummy_user_1"
+    }
+  },
+  "ui": {
+    "forgotPasswordHeading": "Forgot password?"
+  }
+}

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

Comment on lines +39 to +41
loginPage.interceptResetLinkReq();
loginPage.clickSendResetLinkBtn();
loginPage.verifyResetLinkReq();
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 API response verification.

Enhance API interception to verify response status and body:

     loginPage.interceptResetLinkReq();
     loginPage.clickSendResetLinkBtn();
-    loginPage.verifyResetLinkReq();
+    // Verify API response
+    cy.wait('@resetLinkReq').then((interception) => {
+      expect(interception.response.statusCode).to.equal(200);
+      expect(interception.response.body).to.have.property('message', 'Reset link sent successfully');
+    });

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

Comment on lines +12 to +19
it("Log in as admin with correct password", () => {
loginPage.loginManuallyAsDistrictAdmin();
loginPage.interceptFacilityReq();
loginPage.verifyFacilityReq();
loginPage.ensureLoggedIn();
loginPage.clickSignOutBtn();
loginPage.verifyLoginPageUrl();
});
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 test stability and coverage for successful login.

The test needs the following improvements:

  1. Move API interception before the login action
  2. Add retry mechanism for flaky scenarios
  3. Add validation for UI elements
-  it("Log in as admin with correct password", () => {
+  it("should successfully log in as admin and verify facility access", { retries: 2 }, () => {
+    loginPage.interceptFacilityReq();
     loginPage.loginManuallyAsDistrictAdmin();
-    loginPage.interceptFacilityReq();
     loginPage.verifyFacilityReq();
     loginPage.ensureLoggedIn();
+    // Verify UI elements after successful login
+    cy.get('#user-profile-name').should('be.visible');
     loginPage.clickSignOutBtn();
     loginPage.verifyLoginPageUrl();
   });
📝 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
it("Log in as admin with correct password", () => {
loginPage.loginManuallyAsDistrictAdmin();
loginPage.interceptFacilityReq();
loginPage.verifyFacilityReq();
loginPage.ensureLoggedIn();
loginPage.clickSignOutBtn();
loginPage.verifyLoginPageUrl();
});
it("should successfully log in as admin and verify facility access", { retries: 2 }, () => {
loginPage.interceptFacilityReq();
loginPage.loginManuallyAsDistrictAdmin();
loginPage.verifyFacilityReq();
loginPage.ensureLoggedIn();
// Verify UI elements after successful login
cy.get('#user-profile-name').should('be.visible');
loginPage.clickSignOutBtn();
loginPage.verifyLoginPageUrl();
});

Comment on lines +30 to +48
describe("Reset user's password using email", () => {
beforeEach(() => {
cy.awaitUrl("/", true);
});

it("Send a password reset link and navigate back to the login page", () => {
loginPage.clickForgotPasswordButton(forgotPasswordHeading);
loginPage.verifyForgotPasswordHeading([forgotPasswordHeading]);
loginPage.fillUserNameInForgotPasswordForm(userName);
loginPage.interceptResetLinkReq();
loginPage.clickSendResetLinkBtn();
loginPage.verifyResetLinkReq();
cy.verifyNotification("Password Reset Email Sent");
cy.closeNotification();
loginPage.clickBackButton();
loginPage.verifyLoginPageUrl();
loginPage.verifyLoginButtonPresence();
});
});
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

Combine password reset tests and add negative scenarios.

As per PR objectives and previous review comments:

  1. Combine all three password reset test cases into one comprehensive test
  2. Add negative test cases for invalid scenarios
  3. Add validation for edge cases
 describe("Reset user's password using email", () => {
+  const forgotPasswordHeading = "Forgot password?";
+
   beforeEach(() => {
     cy.awaitUrl("/", true);
+    cy.fixture('auth.json').as('authData');
   });

-  it("Send a password reset link and navigate back to the login page", () => {
+  it("should handle password reset workflow with various scenarios", () => {
+    // Test Case 1: Invalid email format
+    loginPage.clickForgotPasswordButton(forgotPasswordHeading);
+    loginPage.fillUserNameInForgotPasswordForm("invalid@email");
+    cy.get('button[type="submit"]').should('be.disabled');
+    cy.get('input[name="username"]').should('have.class', 'error');
+
+    // Test Case 2: Non-existent user
+    loginPage.fillUserNameInForgotPasswordForm("[email protected]");
+    loginPage.interceptResetLinkReq();
+    loginPage.clickSendResetLinkBtn();
+    loginPage.verifyResetLinkReq();
+    cy.verifyNotification("User not found");
+    cy.closeNotification();
+
+    // Test Case 3: Successful password reset
     loginPage.clickForgotPasswordButton(forgotPasswordHeading);
     loginPage.verifyForgotPasswordHeading([forgotPasswordHeading]);
     loginPage.fillUserNameInForgotPasswordForm(userName);
     loginPage.interceptResetLinkReq();
     loginPage.clickSendResetLinkBtn();
     loginPage.verifyResetLinkReq();
     cy.verifyNotification("Password Reset Email Sent");
     cy.closeNotification();
     loginPage.clickBackButton();
     loginPage.verifyLoginPageUrl();
     loginPage.verifyLoginButtonPresence();
   });
 });
📝 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
describe("Reset user's password using email", () => {
beforeEach(() => {
cy.awaitUrl("/", true);
});
it("Send a password reset link and navigate back to the login page", () => {
loginPage.clickForgotPasswordButton(forgotPasswordHeading);
loginPage.verifyForgotPasswordHeading([forgotPasswordHeading]);
loginPage.fillUserNameInForgotPasswordForm(userName);
loginPage.interceptResetLinkReq();
loginPage.clickSendResetLinkBtn();
loginPage.verifyResetLinkReq();
cy.verifyNotification("Password Reset Email Sent");
cy.closeNotification();
loginPage.clickBackButton();
loginPage.verifyLoginPageUrl();
loginPage.verifyLoginButtonPresence();
});
});
describe("Reset user's password using email", () => {
const forgotPasswordHeading = "Forgot password?";
beforeEach(() => {
cy.awaitUrl("/", true);
cy.fixture('auth.json').as('authData');
});
it("should handle password reset workflow with various scenarios", () => {
// Test Case 1: Invalid email format
loginPage.clickForgotPasswordButton(forgotPasswordHeading);
loginPage.fillUserNameInForgotPasswordForm("invalid@email");
cy.get('button[type="submit"]').should('be.disabled');
cy.get('input[name="username"]').should('have.class', 'error');
// Test Case 2: Non-existent user
loginPage.fillUserNameInForgotPasswordForm("[email protected]");
loginPage.interceptResetLinkReq();
loginPage.clickSendResetLinkBtn();
loginPage.verifyResetLinkReq();
cy.verifyNotification("User not found");
cy.closeNotification();
// Test Case 3: Successful password reset
loginPage.clickForgotPasswordButton(forgotPasswordHeading);
loginPage.verifyForgotPasswordHeading([forgotPasswordHeading]);
loginPage.fillUserNameInForgotPasswordForm(userName);
loginPage.interceptResetLinkReq();
loginPage.clickSendResetLinkBtn();
loginPage.verifyResetLinkReq();
cy.verifyNotification("Password Reset Email Sent");
cy.closeNotification();
loginPage.clickBackButton();
loginPage.verifyLoginPageUrl();
loginPage.verifyLoginButtonPresence();
});
});

@khavinshankar khavinshankar merged commit a028a6c into ohcnetwork:develop Nov 12, 2024
25 checks passed
Copy link

@JavidSumra Your efforts have helped advance digital healthcare and TeleICU systems. 🚀 Thank you for taking the time out to make CARE better. We hope you continue to innovate and contribute; your impact is immense! 🙌

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