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

test: Add more coverage for connect card validators #3411

Conversation

bistaastha
Copy link
Contributor

@bistaastha bistaastha commented Jan 8, 2025

Coverage:
Screenshot 2025-01-08 at 10 04 28 AM

Summary by CodeRabbit

  • Tests

    • Enhanced test coverage for spender onboarding connect card step component
    • Added new test methods for error handling and card number updates
    • Improved test scenarios for message generation and error popover display
    • Integrated new services for better testing of onboarding flows
  • Bug Fixes

    • Updated error handling mechanisms in component
    • Refined message generation logic for card enrollment failures
  • New Features

    • Introduced new output event for navigating back to connect card step
    • Added conditional navigation logic based on organization settings and onboarding status
  • Refactor

    • Converted showErrorPopover method to asynchronous function
    • Made handleEnrollmentFailures method more flexible with optional parameters
    • Centralized navigation logic in the Invited User Page component

Copy link

coderabbitai bot commented Jan 8, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request enhances the SpenderOnboardingConnectCardStepComponent and related components with improved testing and functionality. New methods for error handling, messaging, and card number validation have been introduced, making the component more robust. The changes also include updates to the test suite, ensuring comprehensive coverage and better error management across the onboarding process.

Changes

File Change Summary
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.spec.ts - Added generateMessage(), showErrorPopover(), and onCardNumberUpdate() methods
- Updated import statements
- Enhanced test coverage for error handling and card validation
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts - Modified showErrorPopover() to be async
- Updated handleEnrollmentFailures() with optional cardId
- Refined message generation logic
src/app/auth/switch-org/switch-org.page.spec.ts - Integrated OrgSettingsService and SpenderOnboardingService into tests
- Expanded test cases for navigateBasedOnUserStatus method
src/app/auth/switch-org/switch-org.page.ts - Updated navigation logic in navigateToDashboard method based on organization settings
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.html - Added disabled state for "Continue" button based on form validity
src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.html - Updated mobile number label and restructured CTA container
src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.scss - Renamed and restructured CSS classes for improved layout
src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.spec.ts - Added SpenderOnboardingService to test suite for enhanced testing capabilities
src/app/fyle/spender-onboarding/spender-onboarding.page.html - Added event binding for goToConnectCard event
src/app/fyle/spender-onboarding/spender-onboarding.page.scss - Updated padding and color properties for improved styling
src/app/fyle/spender-onboarding/spender-onboarding.page.spec.ts - Enhanced tests for asynchronous operations using fakeAsync and tick
src/app/fyle/spender-onboarding/spender-onboarding.page.ts - Introduced new method goBackToConnectCard for navigation logic
src/app/post-verification/invited-user/invited-user.page.ts - Added navigateToDashboard method for improved navigation logic
src/app/shared/components/sidemenu/sidemenu.component.spec.ts - Integrated SpenderOnboardingService into tests for onboarding status
src/app/shared/components/sidemenu/sidemenu.component.ts - Added reloadSidemenu method for refreshing side menu

Possibly related PRs

  • feat: Add UI and controller for Opt in step #3390: The changes in the main PR involve the implementation of the Opt-in step for onboarding, which is directly related to the onboarding process and user interactions.
  • feat: Connect Card validation fixes #3391: The modifications in the main PR focus on validation fixes for the Connect Card step, which aligns with the changes in the retrieved PRs that also enhance the error handling and validation processes for card enrollment.
  • test: test for opt in and connect card #3406: The main PR introduces tests for the Opt-in and Connect Card steps, which are directly related to the changes in the retrieved PRs that enhance the functionality and user experience of these onboarding steps.
  • test: Add more coverage for connect card validators #3411: The main PR adds more coverage for connect card validators, which is directly related to the changes in the retrieved PRs that enhance the validation logic and error handling for card enrollment.
  • test: Fix tests related to newer imports #3412: The main PR focuses on fixing tests related to newer imports, which is relevant to the changes in the retrieved PRs that update the test suite to accommodate new service dependencies and functionalities.

Suggested Reviewers

  • arjunaj5
  • Chethan-Fyle
  • Dimple16

Poem

In the land of code, where logic flows,
New methods bloom, like a garden that grows!
Errors flee, as tests take flight,
Rajinikanth's magic, shining so bright!
💥🚀 Let’s celebrate this coding delight! 🌟


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73f752e and 9250085.

📒 Files selected for processing (15)
  • src/app/auth/switch-org/switch-org.page.spec.ts (6 hunks)
  • src/app/auth/switch-org/switch-org.page.ts (1 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.html (1 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts (4 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.html (2 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.scss (5 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.spec.ts (6 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-opt-in-step/spender-onboarding-opt-in-step.component.ts (8 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.html (1 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.scss (2 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.spec.ts (4 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding.page.ts (5 hunks)
  • src/app/post-verification/invited-user/invited-user.page.ts (5 hunks)
  • src/app/shared/components/sidemenu/sidemenu.component.spec.ts (8 hunks)
  • src/app/shared/components/sidemenu/sidemenu.component.ts (1 hunks)

Finishing Touches

  • 📝 Generate Docstrings

🪧 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.

@github-actions github-actions bot added the size/M Medium PR label Jan 8, 2025
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: 4

🔭 Outside diff range comments (1)
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts (1)

Line range hint 254-262: Let's add some punch dialogues to our error messages!

The error handling is good, but we could make the error messages more specific based on different failure scenarios.

Consider categorizing errors and providing more specific messages:

   private handleEnrollmentFailures(error: Error, cardId?: string): void {
-    const enrollmentFailureMessage = error.message || 'Something went wrong. Please try after some time.';
+    const enrollmentFailureMessage = error.message || this.getSpecificErrorMessage(error);
     if (this.enrollableCards.length > 0) {
       this.fg.controls[`card_number_${cardId}`].setErrors({ enrollmentError: true });
       this.cardValuesMap[cardId].enrollment_error = enrollmentFailureMessage;
     } else {
       this.fg.controls.card_number.setErrors({ enrollmentError: true });
       this.singularEnrollmentFailure = enrollmentFailureMessage;
     }
   }
+
+  private getSpecificErrorMessage(error: Error): string {
+    // Add specific error messages based on error types
+    if (error instanceof HttpErrorResponse) {
+      switch (error.status) {
+        case 400: return 'Invalid card details provided';
+        case 409: return 'This card is already enrolled';
+        default: return 'Something went wrong. Please try after some time';
+      }
+    }
+    return 'Something went wrong. Please try after some time';
+  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2d3cd5 and 73f752e.

📒 Files selected for processing (2)
  • src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.spec.ts (6 hunks)
  • src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts (4 hunks)
🧰 Additional context used
📓 Learnings (1)
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.spec.ts (1)
Learnt from: bistaastha
PR: fylein/fyle-mobile-app#3240
File: src/app/fyle/manage-corporate-cards/manage-corporate-cards.page.spec.ts:200-200
Timestamp: 2024-11-12T04:53:12.395Z
Learning: In 'src/app/fyle/manage-corporate-cards/manage-corporate-cards.page.spec.ts', moving 'component.isAddCorporateCardVisible$ = of(true);' to the top-level beforeEach block causes tests to fail, so mock values need to be set in individual tests.
🪛 Biome (1.9.4)
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts

[error] 14-14: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

🪛 eslint
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts

[error] 14-14: 'error' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Run linters
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts

[failure] 14-14:
'error' is defined but never used

🪛 GitHub Actions: Lint
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts

[error] 3-3: 'ChangeDetectorRef' is defined but never used

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build (12.x)
🔇 Additional comments (2)
src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.ts (1)

Line range hint 154-181: Superstar code right here!

The async/await implementation is clean and handles the popover display elegantly. Mind-blowing error handling, macha!

src/app/fyle/spender-onboarding/spender-onboarding-connect-card-step/spender-onboarding-connect-card-step.component.spec.ts (1)

177-215: Kabali style testing, macha!

The test coverage for generateMessage is solid! All scenarios are covered with proper assertions.

@@ -11,7 +11,8 @@
} from '@angular/core';
import { AbstractControl, FormBuilder, FormControl, FormGroup, ValidationErrors, Validators } from '@angular/forms';
import { PopoverController } from '@ionic/angular';
import { error } from 'console';
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Mind it! Remove unused import, macha!

The import 'error' from 'console' is not being used anywhere in the code. Let's keep our imports clean and tidy!

-import { error } from 'console';
🧰 Tools
🪛 Biome (1.9.4)

[error] 14-14: A Node.js builtin module should be imported with the node: protocol.

Using the node: protocol is more explicit and signals that the imported module belongs to Node.js.
Unsafe fix: Add the node: protocol.

(lint/style/useNodejsImportProtocol)

🪛 eslint

[error] 14-14: 'error' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: Run linters

[failure] 14-14:
'error' is defined but never used

Comment on lines +143 to +150
} else if (this.cardsList.failedCards.length > 1) {
return `We ran into an issue while processing your request for the cards ${this.cardsList.failedCards
.slice(0, this.cardsList.failedCards.length - 1)
.join(', ')} and ${this.cardsList.failedCards.slice(-1)}.
You can cancel and retry connecting the failed card or proceed to the next step.`;
.join(', ')} and ${this.cardsList.failedCards.slice(
-1
)}. You can cancel and retry connecting the failed card or proceed to the next step.`;
} else {
return `
We ran into an issue while processing your request for the card ${this.cardsList.failedCards[0]}.
You can cancel and retry connecting the failed card or proceed to the next step.`;
return `We ran into an issue while processing your request for the card ${this.cardsList.failedCards[0]}. You can cancel and retry connecting the failed card or proceed to the next step.`;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Style ah style! Let's make this code more stylish!

The string concatenation can be simplified using template literals for better readability, macha!

    } else if (this.cardsList.failedCards.length > 1) {
-      return `We ran into an issue while processing your request for the cards  ${this.cardsList.failedCards
-        .slice(0, this.cardsList.failedCards.length - 1)
-        .join(', ')} and ${this.cardsList.failedCards.slice(
-        -1
-      )}. You can cancel and retry connecting the failed card or proceed to the next step.`;
+      const allButLast = this.cardsList.failedCards.slice(0, -1).join(', ');
+      const lastCard = this.cardsList.failedCards.slice(-1);
+      return `We ran into an issue while processing your request for the cards ${allButLast} and ${lastCard}. You can cancel and retry connecting the failed card or proceed to the next step.`;
📝 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
} else if (this.cardsList.failedCards.length > 1) {
return `We ran into an issue while processing your request for the cards ${this.cardsList.failedCards
.slice(0, this.cardsList.failedCards.length - 1)
.join(', ')} and ${this.cardsList.failedCards.slice(-1)}.
You can cancel and retry connecting the failed card or proceed to the next step.`;
.join(', ')} and ${this.cardsList.failedCards.slice(
-1
)}. You can cancel and retry connecting the failed card or proceed to the next step.`;
} else {
return `
We ran into an issue while processing your request for the card ${this.cardsList.failedCards[0]}.
You can cancel and retry connecting the failed card or proceed to the next step.`;
return `We ran into an issue while processing your request for the card ${this.cardsList.failedCards[0]}. You can cancel and retry connecting the failed card or proceed to the next step.`;
} else if (this.cardsList.failedCards.length > 1) {
const allButLast = this.cardsList.failedCards.slice(0, -1).join(', ');
const lastCard = this.cardsList.failedCards.slice(-1);
return `We ran into an issue while processing your request for the cards ${allButLast} and ${lastCard}. You can cancel and retry connecting the failed card or proceed to the next step.`;
} else {
return `We ran into an issue while processing your request for the card ${this.cardsList.failedCards[0]}. You can cancel and retry connecting the failed card or proceed to the next step.`;

Comment on lines +296 to +329
it('showErrorPopover(): should display a popover and handle its actions', () => {
const popoverSpy = jasmine.createSpyObj('popover', ['present', 'onWillDismiss']);
spyOn(component, 'generateMessage').and.returnValue('Error message');
popoverSpy.onWillDismiss.and.resolveTo({
data: {
action: 'close',
},
});
popoverController.create.and.resolveTo(popoverSpy);
component.cardsList = {
successfulCards: [],
failedCards: ['**** 1111'],
};
fixture.detectChanges();
component.showErrorPopover();

expect(popoverController.create).toHaveBeenCalledOnceWith({
componentProps: {
title: 'Failed connecting',
message: 'Error message',
primaryCta: {
text: 'Proceed anyway',
action: 'close',
},
secondaryCta: {
text: 'Cancel',
action: 'cancel',
},
cardsList: {},
},
component: PopupAlertComponent,
cssClass: 'pop-up-in-center',
});
});
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Time to level up our testing game!

The test verifies popover creation, but let's add a test for the dismiss scenario too!

Add this test case:

it('should handle popover dismiss with cancel action', async () => {
  const popoverSpy = jasmine.createSpyObj('popover', ['present', 'onWillDismiss']);
  spyOn(component, 'generateMessage').and.returnValue('Error message');
  popoverSpy.onWillDismiss.and.resolveTo({
    data: {
      action: 'cancel'
    }
  });
  popoverController.create.and.resolveTo(popoverSpy);
  
  const stepCompleteSpy = spyOn(component.isStepComplete, 'emit');
  await component.showErrorPopover();
  
  expect(stepCompleteSpy).not.toHaveBeenCalled();
});

Comment on lines +342 to +343
it('should update card_type for the given card or singleEnrollableCardDetails', () => {
realTimeFeedService.getCardTypeFromNumber.and.returnValue(CardNetworkType.VISA);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Duplicate test description spotted, thalaiva!

Both test cases have the same description. Let's make them more specific!

-    it('should update card_type for the given card or singleEnrollableCardDetails', () => {
+    it('should update card_type in cardValuesMap for multiple enrollable cards', () => {
📝 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('should update card_type for the given card or singleEnrollableCardDetails', () => {
realTimeFeedService.getCardTypeFromNumber.and.returnValue(CardNetworkType.VISA);
it('should update card_type in cardValuesMap for multiple enrollable cards', () => {
realTimeFeedService.getCardTypeFromNumber.and.returnValue(CardNetworkType.VISA);

@github-actions github-actions bot added the size/L Large PR label Jan 9, 2025
@bistaastha bistaastha merged commit 24fb103 into FYLE-86cx2t82k-tests-for-connect-card-2 Jan 9, 2025
5 of 6 checks passed
@github-actions github-actions bot removed the size/M Medium PR label Jan 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/L Large PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants