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 tests for Corporate Card task #3370

Merged
merged 7 commits into from
Dec 19, 2024

Conversation

bistaastha
Copy link
Contributor

@bistaastha bistaastha commented Dec 18, 2024

Follow up to: #3362

Summary by CodeRabbit

  • New Features

    • Added support for managing corporate cards, including a new task event and task icons.
    • Introduced functionality for adding corporate cards through a popover interface.
    • Enhanced task handling with new methods for corporate card enrollment success and task routing.
  • Bug Fixes

    • Improved test coverage and functionality for various components related to corporate card management.
  • Tests

    • Expanded test cases to cover new features and interactions, ensuring robust component behavior.

Copy link

coderabbitai bot commented Dec 18, 2024

Caution

Review failed

The head commit changed during the review from f63791a to 8787ab3.

Walkthrough

With the power of a thousand supercomputers, I bring forth a transformation in the corporate card management realm! A new task event has emerged, expanding the horizons of our application. The changes introduce a comprehensive approach to corporate card enrollment, weaving new methods into the fabric of our tasks service and component. Like a digital superhero, the code now dances with enhanced capabilities to handle corporate card interactions!

Changes

File Change Summary
src/app/core/models/task-event.enum.ts Added addCorporateCard = 10 enum entry
src/app/core/models/task-icon.enum.ts Added CARD = 'card' to TaskIcon enum
src/app/core/services/tasks.service.ts Added getAddCorporateCardTask() and mapAddCorporateCardTask() methods
src/app/fyle/dashboard/tasks/tasks.component.ts Added new methods for corporate card handling, updated task click logic

Sequence Diagram

sequenceDiagram
    participant User
    participant TasksComponent
    participant TasksService
    participant PopoverController
    participant CorporateCreditCardService

    User->>TasksComponent: Click Add Corporate Card
    TasksComponent->>PopoverController: Create Popover
    PopoverController-->>User: Show Add Card Options
    User->>CorporateCreditCardService: Initiate Card Enrollment
    CorporateCreditCardService-->>TasksComponent: Update Task Status
    TasksComponent->>TasksService: Refresh Tasks
Loading

Possibly related PRs

Suggested Labels

size/L

Suggested Reviewers

  • Chethan-Fyle
  • arjunaj5
  • Dimple16

Poem

Behold, a digital dance of might,
Corporate cards take their flight!
Enum entries spark with glee, 🃏
Tasks now flow more free! 💥
Rajinikanth's code - pure delight! 🌟


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

@github-actions github-actions bot added the size/M Medium PR label Dec 18, 2024
@bistaastha bistaastha changed the base branch from master to FYLE-cc-card-task December 18, 2024 06:13
Asset: 'Mobile',
header: task.header,
});
// eslint-disable-next-line complexity
Copy link
Contributor Author

Choose a reason for hiding this comment

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

will raise a follow up PR to fix this

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments.

Actionable comments posted: 9

🔭 Outside diff range comments (1)
src/app/fyle/dashboard/tasks/tasks.component.ts (1)

Line range hint 403-447: Switch-case style: Crisp, clear, and unstoppable!
Renaming from 'onTaskClicked' to 'loadTasksMap' is okay, but the new name might be less intuitive for the uninitiated. Keep that in mind, thalaiva!

🛑 Comments failed to post (9)
src/app/fyle/dashboard/tasks/tasks.component.ts (2)

474-484: 🧹 Nitpick (assertive)

Enrollment success flow is top-notch!
Clearing the cache and showing the success popover is a triumphant approach. Perhaps also handle potential errors from clearCache() to keep the user journey silky smooth.


486-507: 🛠️ Refactor suggestion

Corporate card popover? That’s how we do it, boss!
The forking setup is impressive. If an error occurs in these calls, you might want to handle or notify the user, though. Keep your fans happy.

+        // Add error handling inside subscribe
+        // e.g., catchError(...) or a graceful user-facing message

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

src/app/fyle/dashboard/tasks/tasks-1.component.spec.ts (2)

44-45: 🧹 Nitpick (assertive)

Mind-blowing! But let's add more test coverage, macha!

The imports look good, but we need more test coverage for OrgSettingsService, like testing different scenarios when org settings are not available.


93-96: 🛠️ Refactor suggestion

Style ah style! But let's make it more robust!

The test setup looks good, but consider adding negative test cases:

 orgSettingsService.get.and.returnValue(of(orgSettingsPendingRestrictions));
 component.isVisaRTFEnabled$ = of(true);
 component.isMastercardRTFEnabled$ = of(true);
 component.isYodleeEnabled$ = of(true);
+
+// Add negative test case
+it('should handle when org settings are not available', () => {
+  orgSettingsService.get.and.returnValue(of(null));
+  fixture.detectChanges();
+  expect(component.setupNetworkWatcher).toHaveBeenCalledTimes(1);
+});

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

src/app/fyle/dashboard/tasks/tasks-2.component.spec.ts (1)

203-232: 🛠️ Refactor suggestion

Kabali style testing! But let's add more power to it!

The test for onAddCorporateCardClick is well-written, but let's add error handling scenarios:

 it('onAddCorporateCardClick(): should open card popover', fakeAsync(() => {
   // Existing test code...
 }));

+it('should handle popover creation failure', fakeAsync(() => {
+  component.isVisaRTFEnabled$ = of(true);
+  component.isMastercardRTFEnabled$ = of(true);
+  component.isYodleeEnabled$ = of(true);
+
+  popoverController.create.and.rejectWith(new Error('Failed to create popover'));
+
+  component.onAddCorporateCardClick();
+  tick();
+
+  expect(popoverController.create).toHaveBeenCalled();
+}));

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

src/app/core/services/tasks.service.ts (2)

585-601: 🧹 Nitpick (assertive)

Single-ah style! But let's make it type-safe!

The mapAddCorporateCardTask implementation needs type safety:

-mapAddCorporateCardTask(): DashboardTask[] {
+mapAddCorporateCardTask(): DashboardTask[] {
+  interface CardTask {
+    hideAmount: boolean;
+    header: string;
+    subheader: string;
+    icon: TaskIcon;
+    ctas: Array<{
+      content: string;
+      event: TASKEVENT;
+    }>;
+  }
+
   const task = [
-    {
+    <CardTask>{
       hideAmount: true,
       header: 'Add Corporate Card',
       subheader: 'Add your corporate card to track expenses.',

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


534-550: ⚠️ Potential issue

Mind it! Let's add some error handling, thalaiva!

The getAddCorporateCardTask implementation needs error handling:

 getAddCorporateCardTask(): Observable<DashboardTask[]> {
-  return forkJoin([this.orgSettingsService.get(), this.corporateCreditCardExpenseService.getCorporateCards()]).pipe(
+  return forkJoin([
+    this.orgSettingsService.get().pipe(
+      catchError((error) => {
+        console.error('Failed to fetch org settings:', error);
+        return of(null);
+      })
+    ),
+    this.corporateCreditCardExpenseService.getCorporateCards().pipe(
+      catchError((error) => {
+        console.error('Failed to fetch corporate cards:', error);
+        return of([]);
+      })
+    )
+  ]).pipe(
     map(([orgSettings, cards]) => {
+      if (!orgSettings) {
+        return [] as DashboardTask[];
+      }
       const isRtfEnabled =
         (orgSettings.visa_enrollment_settings.allowed && orgSettings.visa_enrollment_settings.enabled) ||
         (orgSettings.mastercard_enrollment_settings.allowed && orgSettings.mastercard_enrollment_settings.enabled);
📝 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.

  getAddCorporateCardTask(): Observable<DashboardTask[]> {
    return forkJoin([
      this.orgSettingsService.get().pipe(
        catchError((error) => {
          console.error('Failed to fetch org settings:', error);
          return of(null);
        })
      ),
      this.corporateCreditCardExpenseService.getCorporateCards().pipe(
        catchError((error) => {
          console.error('Failed to fetch corporate cards:', error);
          return of([]);
        })
      )
    ]).pipe(
      map(([orgSettings, cards]) => {
        if (!orgSettings) {
          return [] as DashboardTask[];
        }
        const isRtfEnabled =
          (orgSettings.visa_enrollment_settings.allowed && orgSettings.visa_enrollment_settings.enabled) ||
          (orgSettings.mastercard_enrollment_settings.allowed && orgSettings.mastercard_enrollment_settings.enabled);
        const isCCCEnabled =
          orgSettings.corporate_credit_card_settings.allowed && orgSettings.corporate_credit_card_settings.enabled;
        const rtfCards = cards.filter((card) => card.is_visa_enrolled || card.is_mastercard_enrolled);
        if (isRtfEnabled && isCCCEnabled && rtfCards.length === 0) {
          return this.mapAddCorporateCardTask();
        } else {
          return [] as DashboardTask[];
        }
      })
    );
  }
src/app/core/services/tasks.service.spec.ts (2)

437-444: 🧹 Nitpick (assertive)

Style-ah test case implementation, but let's add more power to it!

The test case correctly verifies the scenario with enrolled cards. However, we should add one more test case to handle error scenarios.

Add this test case to handle error scenarios:

it('should handle errors gracefully', (done) => {
  corporateCreditCardExpenseService.getCorporateCards.and.returnValue(throwError(() => new Error('API Error')));
  
  tasksService.getAddCorporateCardTask().subscribe({
    error: (err) => {
      expect(corporateCreditCardExpenseService.getCorporateCards).toHaveBeenCalled();
      expect(err.message).toEqual('API Error');
      done();
    }
  });
});

806-806: ⚠️ Potential issue

Aiyyo! We've got a duplicate setup here, machan!

This line is duplicating the corporate card setup that's already done at line 805. Remove this duplicate setup to avoid any potential test inconsistencies.

Apply this change:

-    corporateCreditCardExpenseService.getCorporateCards.and.returnValue(of([mastercardRTFCard]));

@bistaastha bistaastha merged commit df00248 into FYLE-cc-card-task Dec 19, 2024
5 of 6 checks passed
Copy link

Unit Test Coverage % values
Statements 95.94% ( 19327 / 20144 )
Branches 91.04% ( 10679 / 11730 )
Functions 94.18% ( 5748 / 6103 )
Lines 95.98% ( 18456 / 19228 )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/M Medium PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants