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

chore(auth-apis): Add api mocks to tests. #16867

Merged
merged 2 commits into from
Nov 15, 2024
Merged

Conversation

valurefugl
Copy link
Member

@valurefugl valurefugl commented Nov 14, 2024

What

Add api mocks to tests.

Why

To prevent flakiness due to timeouts.

Screenshots / Gifs

Attach Screenshots / Gifs to help reviewers understand the scope of the pull request

Checklist:

  • I have performed a self-review of my own code
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • Formatting passes locally with my changes
  • I have rebased against main before asking for a review

Summary by CodeRabbit

  • New Features

    • Introduced a mock implementation for the CompanyRegistryClientService, enhancing testing scenarios.
    • Expanded the test suite to include additional client services for delegation access testing.
  • Bug Fixes

    • Improved the reliability of tests by mocking external service responses, ensuring isolation from actual service dependencies.
  • Documentation

    • Updated mock exports to include the new CompanyRegistryClientServiceMock, enhancing clarity and organization in the testing framework.

@valurefugl valurefugl requested review from a team as code owners November 14, 2024 13:19
Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in this pull request primarily involve enhancements to the test suite for delegation access functionality. New imports for RskRelationshipsClient and CompanyRegistryClientService have been added to the test file, allowing for the mocking of their methods. Additionally, a new mock implementation of CompanyRegistryClientService has been created to facilitate testing scenarios without relying on actual service responses. The setup file has also been updated to incorporate this mock service, improving the overall testing framework without altering existing logic.

Changes

File Change Summary
apps/services/auth/delegation-api/src/app/delegations/test/me-delegations.access-incoming.spec.ts Added imports for RskRelationshipsClient and CompanyRegistryClientService; mocked methods for testing.
apps/services/auth/public-api/test/mocks/companyRegistryClientService.mock.ts Introduced CompanyRegistryClientServiceMock with a method getCompany returning a resolved promise with null.
apps/services/auth/public-api/test/mocks/index.ts Added export for CompanyRegistryClientServiceMock.
apps/services/auth/public-api/test/setup.ts Imported CompanyRegistryClientService and CompanyRegistryClientServiceMock; updated setupWithAuth to use the mock.

Possibly related PRs

Suggested labels

automerge, test everything

Suggested reviewers

  • Herdismaria
  • baering
  • lodmfjord

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.

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

codecov bot commented Nov 14, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 36.43%. Comparing base (e783a75) to head (a0b5bd6).
Report is 1 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #16867      +/-   ##
==========================================
- Coverage   36.44%   36.43%   -0.02%     
==========================================
  Files        6851     6852       +1     
  Lines      143572   143585      +13     
  Branches    40983    40977       -6     
==========================================
- Hits        52328    52311      -17     
- Misses      91244    91274      +30     
Flag Coverage Δ
api 3.34% <ø> (ø)
api-domains-auth-admin 48.48% <ø> (ø)
application-system-api 40.99% <ø> (ø)
application-template-api-modules 27.66% <ø> (+<0.01%) ⬆️
judicial-system-backend 55.13% <ø> (ø)
services-auth-delegation-api 57.51% <ø> (-0.71%) ⬇️
services-auth-ids-api 52.08% <ø> (ø)
services-auth-public-api 48.90% <100.00%> (-0.70%) ⬇️
services-user-notification 46.92% <ø> (ø)
services-user-profile 61.81% <ø> (-0.08%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...pi/test/mocks/companyRegistryClientService.mock.ts 100.00% <100.00%> (ø)
apps/services/auth/public-api/test/mocks/index.ts 100.00% <100.00%> (ø)

... and 12 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update e783a75...a0b5bd6. Read the comment docs.

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 (4)
apps/services/auth/public-api/test/mocks/companyRegistryClientService.mock.ts (1)

3-8: Consider enhancing the mock implementation.

While the current implementation is functional, it could be improved to better support various test scenarios:

  1. The mock could support configurable responses for different test cases
  2. It might be beneficial to implement more methods from the original service
  3. Consider adding jest.fn() to track method calls during testing

Here's a suggested enhancement:

-export const CompanyRegistryClientServiceMock: Partial<CompanyRegistryClientService> = {
-  getCompany() {
-    return Promise.resolve(null)
-  },
-}
+export class CompanyRegistryClientServiceMock implements Partial<CompanyRegistryClientService> {
+  getCompany = jest.fn().mockResolvedValue(null);
+
+  // Allow setting custom responses for different test scenarios
+  setCompanyResponse(response: any) {
+    this.getCompany.mockResolvedValue(response);
+  }
+}

This enhancement would:

  • Make the mock more flexible for different test scenarios
  • Allow tracking of method calls using jest.spyOn()
  • Maintain type safety with the original service interface
apps/services/auth/public-api/test/setup.ts (1)

Line range hint 1-240: Consider extracting mock providers into a shared configuration.

The test setup is well-organized, but as more mock services are added, consider creating a shared mock provider configuration to improve maintainability. This could be a separate function or constant that groups all mock providers together.

Example approach:

const mockProviders = {
  NationalRegistryClientService: (user: IndividualDto) => 
    createMockEinstaklingurApi(user),
  RskRelationshipsClient: RskProcuringClientMock,
  CompanyRegistryClientService: CompanyRegistryClientServiceMock,
  // ... other mocks
};

// Then in setupWithAuth:
.overrideProviders(Object.entries(mockProviders).map(([key, value]) => ({
  provide: key,
  useValue: typeof value === 'function' ? value(nationalRegistryUser) : value,
})))
apps/services/auth/delegation-api/src/app/delegations/test/me-delegations.access-incoming.spec.ts (2)

Line range hint 46-69: Consider enhancing mock implementations for better test coverage.

While the basic mocking setup is correct, consider these improvements:

  1. Add test cases for error scenarios
  2. Implement more realistic mock responses instead of just null values
  3. Consider testing edge cases with different response shapes

Example enhancement:

 jest
   .spyOn(rskRelationshipsClientService, 'getIndividualRelationships')
-  .mockImplementation(async () => null)
+  .mockImplementation(async () => ({
+    relationships: [],
+    metadata: { total: 0 }
+  }))
 jest
   .spyOn(companyRegistryClientService, 'getCompany')
-  .mockImplementation(async () => null)
+  .mockImplementation(async () => ({
+    name: 'Test Company',
+    id: '1234567890',
+    status: 'active'
+  }))

Also consider adding test cases for:

  • API errors
  • Network timeouts
  • Invalid response formats

Line range hint 1-199: Well-structured test suite following NestJS best practices.

The test suite demonstrates good practices:

  • Proper use of TestApp and dependency injection
  • Clear test organization with describe blocks
  • Comprehensive CRUD operation coverage
  • Good separation of concerns

Consider adding integration tests to verify the interaction between these mocked services in real-world scenarios.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between e47d2b9 and 3617357.

📒 Files selected for processing (4)
  • apps/services/auth/delegation-api/src/app/delegations/test/me-delegations.access-incoming.spec.ts (3 hunks)
  • apps/services/auth/public-api/test/mocks/companyRegistryClientService.mock.ts (1 hunks)
  • apps/services/auth/public-api/test/mocks/index.ts (1 hunks)
  • apps/services/auth/public-api/test/setup.ts (3 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
apps/services/auth/delegation-api/src/app/delegations/test/me-delegations.access-incoming.spec.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/auth/public-api/test/mocks/companyRegistryClientService.mock.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/auth/public-api/test/mocks/index.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
apps/services/auth/public-api/test/setup.ts (2)

Pattern apps/services/**/*: "Confirm that the code adheres to the following:

  • NestJS architecture, including modules, services, and controllers.
  • Dependency injection patterns and service encapsulation.
  • Integration and unit testing coverage and practices."

Pattern apps/**/*: "Confirm that the code adheres to the following:

  • NextJS best practices, including file structure, API routes, and static generation methods.
  • Efficient state management and server-side rendering techniques.
  • Optimal use of TypeScript for component and utility type safety."
🔇 Additional comments (5)
apps/services/auth/public-api/test/mocks/index.ts (1)

4-4: LGTM! The export follows established patterns.

The addition of CompanyRegistryClientService mock export follows the existing barrel file pattern and NestJS testing practices.

Let's verify the mock implementation exists:

✅ Verification successful

Mock implementation exists and follows the expected pattern

The verification confirms that:

  • The mock file exists at the expected location
  • It properly imports and implements the CompanyRegistryClientService interface
  • The getCompany() method is implemented with a basic Promise.resolve(null) response
  • The implementation uses a type-safe approach with Partial
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the CompanyRegistryClientService mock file exists and contains the expected mock implementation

# Check if the mock file exists and show its content
fd "companyRegistryClientService.mock.ts" --type f --exec cat {}

# Verify the mock is properly implemented with expected methods
ast-grep --pattern 'class $_Mock {
  $$$
  getCompany($$$) {
    $$$
  }
  $$$
}'

Length of output: 394

apps/services/auth/public-api/test/mocks/companyRegistryClientService.mock.ts (1)

1-1: LGTM! Clean import statement.

The import is correctly sourced from the clients module, maintaining proper module boundaries.

apps/services/auth/public-api/test/setup.ts (2)

19-19: LGTM! Clean import organization.

The new imports for CompanyRegistryClientService and its mock are well-organized, following the established pattern of separating client services from their mocks.

Also applies to: 39-39


161-162: LGTM! Proper mock service integration.

The mock service is correctly integrated using NestJS's dependency injection system, which will help reduce test flakiness as intended.

Let's verify the mock implementation:

✅ Verification successful

Mock service implementation verified and properly structured

The mock service is correctly implemented and integrated:

  • Mock is defined in a dedicated file companyRegistryClientService.mock.ts
  • It implements Partial<CompanyRegistryClientService> with required methods
  • Properly imported and used in the test setup
  • Integration follows NestJS's dependency injection pattern with .overrideProvider().useValue()
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the CompanyRegistryClientServiceMock implementation

# Check the mock implementation
rg -A 5 "CompanyRegistryClientServiceMock.*=.*{" ./apps/services/auth/public-api/test/mocks/

# Verify usage in tests
rg "CompanyRegistryClientService" ./apps/services/auth/public-api/test/ -g "*.spec.ts"

Length of output: 321


Script:

#!/bin/bash
# Let's fix the regex and try again with separate commands

# Check for mock implementation
rg "CompanyRegistryClientServiceMock" ./apps/services/auth/public-api/test/

# Look for the actual service usage in test files
rg "CompanyRegistryClientService" ./apps/services/auth/public-api/test/ -A 3

# Check for any mock files containing CompanyRegistry
fd "company.*mock" ./apps/services/auth/public-api/test/

Length of output: 2529

apps/services/auth/delegation-api/src/app/delegations/test/me-delegations.access-incoming.spec.ts (1)

12-12: LGTM! New client imports are properly organized.

The new imports for RskRelationshipsClient and CompanyRegistryClientService are correctly placed and follow the established import pattern.

Also applies to: 14-14

@datadog-island-is
Copy link

datadog-island-is bot commented Nov 14, 2024

Datadog Report

All test runs a757bc0 🔗

10 Total Test Services: 0 Failed, 10 Passed
🔻 Test Sessions change in coverage: 3 decreased, 16 no change

Test Services
This report shows up to 10 services
Service Name Failed Known Flaky New Flaky Passed Skipped Total Time Code Coverage Change Test Service View
api 0 0 0 4 0 2.76s 1 no change Link
api-domains-auth-admin 0 0 0 18 0 12.41s 1 no change Link
application-system-api 0 0 0 112 2 3m 42.62s 1 no change Link
application-template-api-modules 0 0 0 113 0 2m 39.59s 1 no change Link
judicial-system-backend 0 0 0 21134 0 21m 53.4s 1 no change Link
services-auth-delegation-api 0 0 0 262 0 3m 26.04s 1 decreased (-0.74%) Link
services-auth-ids-api 0 0 0 152 0 1m 17.19s 1 no change Link
services-auth-public-api 0 0 0 35 0 28.93s 1 decreased (-0.48%) Link
services-user-notification 0 0 0 51 0 1m 31.85s 1 no change Link
services-user-profile 0 0 0 131 0 29.58s 1 decreased (-0.02%) Link

🔻 Code Coverage Decreases vs Default Branch (3)

  • services-auth-delegation-api - jest 51% (-0.74%) - Details
  • services-auth-public-api - jest 45.83% (-0.48%) - Details
  • services-user-profile - jest 52.58% (-0.02%) - Details

Copy link
Member

@GunnlaugurG GunnlaugurG left a comment

Choose a reason for hiding this comment

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

LGTM

@valurefugl valurefugl added the deprecated:automerge (Disabled) Merge this PR as soon as all checks pass label Nov 15, 2024
@kodiakhq kodiakhq bot merged commit fda8787 into main Nov 15, 2024
46 checks passed
@kodiakhq kodiakhq bot deleted the auth-apis/add-api-mocks branch November 15, 2024 12:57
jonnigs pushed a commit that referenced this pull request Nov 26, 2024
Co-authored-by: Valur Einarsson <valure@live.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
@coderabbitai coderabbitai bot mentioned this pull request Dec 6, 2024
6 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
deprecated:automerge (Disabled) Merge this PR as soon as all checks pass
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants