Skip to content

Removed ts-ignore statements from codebase and fixed the tests in faulty files #3253

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

Merged
merged 13 commits into from
Mar 1, 2025

Conversation

yugal07
Copy link

@yugal07 yugal07 commented Feb 19, 2025

What kind of change does this PR introduce?

Bugfix

Issue Number:

Fixes #3228

Snapshots/Videos:

N/A

If relevant, did you update the documentation?
Auto-generated docs

Summary

Some files had ts-ignore statements which is considered to be bad practices, This PR fixes the faulty test files with proper tests and removes ts-ignore statements

Does this PR introduce a breaking change?

No

Checklist

CodeRabbit AI Review

  • I have reviewed and addressed all critical issues flagged by CodeRabbit AI
  • I have implemented or provided justification for each non-critical suggestion
  • I have documented my reasoning in the PR comments where CodeRabbit AI suggestions were not implemented

Test Coverage

  • I have written tests for all new changes/features
  • I have verified that test coverage meets or exceeds 95%
  • I have run the test suite locally and all tests pass

Have you read the contributing guide?

Yes

Summary by CodeRabbit

  • Tests
    • Enhanced type definitions for user roles and mock implementations in tests.
    • Updated mock return values to align with asynchronous behavior.
    • Expanded test coverage for various user scenarios, ensuring consistency and reliability in testing.
    • Refined import paths for improved clarity and structure.
    • Introduced a new test suite for the Chat.updater resolver, validating behavior under various conditions.
    • Added tests for unauthorized access and unauthenticated scenarios.

Copy link

coderabbitai bot commented Feb 19, 2025

Warning

Rate limit exceeded

@yugal07 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 10 minutes and 2 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c957a7b and ea6266e.

📒 Files selected for processing (1)
  • test/graphql/types/Chat/updater.test.ts (1 hunks)

Walkthrough

This pull request introduces several modifications across multiple test files and a source file, focusing on updating import paths, enhancing type definitions, and refining mock implementations. The changes include the introduction of new types related to user roles and mock clients, which improve type safety and clarity in the tests. Additionally, adjustments to mock return values and test cases have been made to ensure consistency and accuracy in testing various scenarios, particularly concerning user authentication and authorization.

Changes

File(s) Changed Change Summary
test/graphql/types/Chat/updatedAt.test.ts, test/graphql/types/Event/updater.test.ts Updated import paths for PubSub and respective resolver functions to a more explicit four-directory path. Added new type definitions for UserRole, ChatMembershipRole, OrganizationMembershipRole, UserObject, MockUser, and MockDrizzleClient. Updated mock implementations of drizzleClientMock to enhance type safety and consistency in tests, including changes to return values from mockReturnValue to mockResolvedValue for asynchronous behavior.
src/graphql/types/Chat/updater.ts Introduced a new function resolveUpdater that encapsulates logic for user authentication and authorization in the Chat implementation. Simplified the resolve method to call resolveUpdater, enhancing code organization and readability.
test/graphql/types/Chat/updater.test.ts Added a new test suite for the Chat.updater resolver, covering various scenarios such as unauthenticated access, unauthorized access, and correct user retrieval based on roles. Used mock implementations for database queries to simulate user states and roles, ensuring isolation and accuracy in testing outcomes.

Possibly related PRs

  • Fixes #3070: tests for Funds/updater.ts #3221: The changes in the main PR and the retrieved PR are related as both involve modifications to the resolveUpdater function, enhancing type definitions and mock implementations in their respective test files.
  • Test: src/graphql/types/FundCampaignPledge/updater.ts #3190: The changes in the main PR and the retrieved PR are related as both introduce a resolveUpdater function that encapsulates resolver logic for different types, with similar authentication and authorization checks, and both involve updates to mock implementations and type definitions.
  • tests for src/graphql/types/Event/updater.ts added #3180: The changes in the main PR and the retrieved PR are related as both introduce new resolver functions (resolveUpdater and resolveEventUpdater) and corresponding test suites that validate their behavior, focusing on user authentication and authorization logic.

Suggested labels

ignore-sensitive-files-pr

Suggested reviewers

  • palisadoes

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 generate docstrings to generate docstrings for this 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

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 19, 2025
Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

  1. Ensure the test code coverage for your patch reaches as close to 100% as possible.
  2. Please add a screen shot or validate via a reference to the codecov report to this PR

@yugal07
Copy link
Author

yugal07 commented Feb 22, 2025

@coderabbitai full review

@yugal07
Copy link
Author

yugal07 commented Feb 22, 2025

Screenshot from 2025-02-22 20-47-53
Screenshot from 2025-02-22 20-47-39

I have added additional test cases and both the files are now at 100% coverage. @palisadoes PTAL

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

These files need to be moved to these directories as .test. files like the rest of them. You are not following our convention stated clearly here:

Directories for the renamed .test. files

  1. test/graphql/types/Chat
  2. test/graphql/types/Events

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 23, 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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe51cad and 7e47722.

📒 Files selected for processing (2)
  • test/graphql/types/Chat/updatedAt.test.ts (4 hunks)
  • test/graphql/types/Event/updater.test.ts (9 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (4)
test/graphql/types/Chat/updatedAt.test.ts (2)

2-33: Well-structured type definitions with proper type safety!

The type definitions are well-organized, using zod for type inference and providing clear structures for mocks. This improves type safety and maintainability.


80-157: Excellent test coverage with comprehensive scenarios!

The tests thoroughly cover:

  • Authentication checks
  • Authorization based on user roles
  • Different permission levels (global admin, org admin, chat admin)
  • Edge cases like user not found
test/graphql/types/Event/updater.test.ts (2)

37-44: Clean mock implementation with proper typing!

The mock implementation is well-structured and properly typed using the MockDrizzleClient type.


70-251: Excellent test coverage with proper error handling and logging!

The tests thoroughly cover:

  • Authentication and authorization scenarios
  • Data integrity checks
  • Error cases with proper logging
  • Different user role combinations

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: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7e47722 and e42f4ec.

📒 Files selected for processing (1)
  • test/graphql/types/Event/updater.test.ts (9 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: yugal07
PR: PalisadoesFoundation/talawa-api#3253
File: test/graphql/types/Chat/updatedAt.test.ts:48-54
Timestamp: 2025-02-23T15:57:18.082Z
Learning: When mocking functions with specific return types in Vitest, prefer using `mockImplementation(() => Promise.resolve(value))` over `mockResolvedValue(value)` when dealing with complex types to ensure type safety.
test/graphql/types/Event/updater.test.ts (1)
Learnt from: yugal07
PR: PalisadoesFoundation/talawa-api#3253
File: test/graphql/types/Event/updater.test.ts:139-162
Timestamp: 2025-02-23T16:10:02.480Z
Learning: In test files, prefer keeping mock data separate for each test case instead of extracting common mock objects, as it provides better test isolation and makes future modifications easier without affecting other tests.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (4)
test/graphql/types/Event/updater.test.ts (4)

2-7: LGTM! Import paths have been updated to use absolute paths.

The changes improve maintainability by using absolute paths and adding proper type imports.


9-24: LGTM! Well-structured type definitions using zod.

The type definitions are clear, well-documented, and properly use zod for type safety. The MockDrizzleClient type accurately represents the mock structure.


141-164: LGTM! Well-structured test case with isolated mock data.

The test case follows best practices by keeping mock data separate and clearly documenting the test scenario.


72-252: LGTM! Comprehensive test coverage.

The test suite:

  • Covers authentication and authorization scenarios
  • Handles edge cases (null updaterId, non-existent updater)
  • Verifies behavior for different user roles
  • Includes proper error handling and logging verification

it("throws an unauthenticated error if the current user is not found", async () => {
// @ts-ignore
drizzleClientMock.query.usersTable.findFirst.mockReturnValue(undefined);
drizzleClientMock.query.usersTable.findFirst.mockResolvedValue(undefined);
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider consistent mock implementation approach.

For consistency and better type safety, consider using mockImplementation instead of mockResolvedValue across all test cases:

-		drizzleClientMock.query.usersTable.findFirst.mockResolvedValue(undefined);
+		drizzleClientMock.query.usersTable.findFirst.mockImplementation(() => Promise.resolve(undefined));

Also applies to: 101-105, 122-126, 154-156, 173-173, 190-190, 213-215

Comment on lines 39 to 46
// Create a properly typed mock for drizzleClient
const drizzleClientMock = {
query: {
usersTable: {
findFirst: vi.fn(),
},
},
} as unknown as FastifyInstance["drizzleClient"];
} as unknown as FastifyInstance["drizzleClient"] & MockDrizzleClient;
Copy link

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Consider using mockImplementation for better type safety.

Based on our experience with complex types in Vitest, consider using mockImplementation instead of the direct mock function:

-			findFirst: vi.fn(),
+			findFirst: vi.fn().mockImplementation(() => Promise.resolve(undefined)),
📝 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
// Create a properly typed mock for drizzleClient
const drizzleClientMock = {
query: {
usersTable: {
findFirst: vi.fn(),
},
},
} as unknown as FastifyInstance["drizzleClient"];
} as unknown as FastifyInstance["drizzleClient"] & MockDrizzleClient;
// Create a properly typed mock for drizzleClient
const drizzleClientMock = {
query: {
usersTable: {
findFirst: vi.fn().mockImplementation(() => Promise.resolve(undefined)),
},
},
} as unknown as FastifyInstance["drizzleClient"] & MockDrizzleClient;

@palisadoes
Copy link
Contributor

  1. Please make coderabbit.ai approves your work.
  2. Make sure all tests pass and are valid.
  3. Ensure the test code coverage for your patch reaches as close to 100% as possible.

@PalisadoesFoundation PalisadoesFoundation deleted a comment from codecov bot Feb 23, 2025
@PalisadoesFoundation PalisadoesFoundation deleted a comment from github-actions bot Feb 23, 2025
@PalisadoesFoundation PalisadoesFoundation deleted a comment from codecov bot Feb 24, 2025
Copy link

Our Pull Request Approval Process

Thanks for contributing!

Testing Your Code

Remember, your PRs won't be reviewed until these criteria are met:

  1. We don't merge PRs with poor code quality.
    1. Follow coding best practices such that CodeRabbit.ai approves your PR.
  2. We don't merge PRs with failed tests.
    1. When tests fail, click on the Details link to learn more.
    2. Write sufficient tests for your changes (CodeCov Patch Test). Your testing level must be better than the target threshold of the repository
    3. Tests may fail if you edit sensitive files. Ask to add the ignore-sensitive-files-pr label if the edits are necessary.
  3. We cannot merge PRs with conflicting files. These must be fixed.

Our policies make our code better.

Reviewers

Do not assign reviewers. Our Queue Monitors will review your PR and assign them.
When your PR has been assigned reviewers contact them to get your code reviewed and approved via:

  1. comments in this PR or
  2. our slack channel

Reviewing Your Code

Your reviewer(s) will have the following roles:

  1. arbitrators of future discussions with other contributors about the validity of your changes
  2. point of contact for evaluating the validity of your work
  3. person who verifies matching issues by others that should be closed.
  4. person who gives general guidance in fixing your tests

CONTRIBUTING.md

Read our CONTRIBUTING.md file. Most importantly:

  1. PRs with issues not assigned to you will be closed by the reviewer
  2. Fix the first comment in the PR so that each issue listed automatically closes

Other

  1. 🎯 Please be considerate of our volunteers' time. Contacting the person who assigned the reviewers is not advised unless they ask for your input. Do not @ the person who did the assignment otherwise.
  2. Read the CONTRIBUTING.md file make

Copy link

codecov bot commented Feb 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 48.80%. Comparing base (0aa74c2) to head (ea6266e).
Report is 12 commits behind head on develop-postgres.

Additional details and impacted files
@@                 Coverage Diff                  @@
##           develop-postgres    #3253      +/-   ##
====================================================
+ Coverage             48.36%   48.80%   +0.43%     
====================================================
  Files                   458      458              
  Lines                 34516    34494      -22     
  Branches                966      985      +19     
====================================================
+ Hits                  16695    16834     +139     
+ Misses                17821    17660     -161     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@palisadoes palisadoes left a comment

Choose a reason for hiding this comment

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

The src/graphql/types/Chat/updater.ts file is only showing 13% test code coverage. Please add more comprehensive and valid tests to get this as close to 100% as possible.

  1. Code coverage isn't reporting any significant change in the code health
    1. https://app.codecov.io/gh/PalisadoesFoundation/talawa-api/pull/3253?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=PalisadoesFoundation
  2. Here is the coverage for the file in question. (Scroll down)
    1. https://app.codecov.io/gh/PalisadoesFoundation/talawa-api/blob/develop-postgres/src%2Fgraphql%2Ftypes%2FChat%2Fupdater.ts
    2. https://app.codecov.io/gh/PalisadoesFoundation/talawa-api/tree/develop-postgres?displayType=list
      image

@yugal07
Copy link
Author

yugal07 commented Feb 24, 2025

The files i have worked on are src/graphql/types/Chat/updatedAt.ts and src/graphql/types/Event/updater.ts. Sure i will add tests for src/graphql/types/Chat/updater.ts, thanks for the review

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: 3

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5303fbc and 313d6ae.

📒 Files selected for processing (2)
  • src/graphql/types/Chat/updater.ts (1 hunks)
  • test/graphql/types/Chat/updater.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
test/graphql/types/Chat/updater.test.ts (1)
Learnt from: yugal07
PR: PalisadoesFoundation/talawa-api#3253
File: test/graphql/types/Chat/updatedAt.test.ts:48-54
Timestamp: 2025-02-23T15:57:18.082Z
Learning: When mocking functions with specific return types in Vitest, prefer using `mockImplementation(() => Promise.resolve(value))` over `mockResolvedValue(value)` when dealing with complex types to ensure type safety.
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Run tests for talawa api
  • GitHub Check: Analyse Code With CodeQL (typescript)
🔇 Additional comments (11)
test/graphql/types/Chat/updater.test.ts (6)

1-16: Good job with comprehensive type definitions!

The explicit type definitions using z.infer for UserRole, ChatMembershipRole, and OrganizationMembershipRole provide excellent type safety. This approach ensures that the test matches the actual type definitions used in the application.


18-33: Well-structured mock types

The mock types are well-defined and closely match the shape of the actual database entities, which will make testing more reliable and maintainable.


98-109: Great test organization with comprehensive test cases

The test suite is well-structured with a beforeEach hook to reset mocks and clear tests for various authentication scenarios. This ensures reliable and isolated test execution.


140-154: Good edge case handling

Testing the null updaterId case is important as it represents a valid edge case in the application. The test properly verifies that null is returned when the updaterId is null.


195-215: Strong error handling verification

Good job testing the unexpected error case when an updaterId exists but the user is not found. This test ensures that the application correctly identifies and logs database inconsistency issues.


65-66: 🧹 Nitpick (assertive)

Consider using mockImplementation consistently for type safety

Based on previous learnings in this codebase, it's preferable to use mockImplementation(() => Promise.resolve(undefined)) rather than mockResolvedValue(undefined) for complex types to ensure better type safety.

-			findFirst: vi.fn().mockImplementation(() => Promise.resolve(undefined)),
+			findFirst: vi.fn().mockImplementation(() => Promise.resolve(undefined)),

Likely an incorrect or invalid review comment.

src/graphql/types/Chat/updater.ts (5)

13-102: Excellent extraction of resolver logic into a separate function

The resolveUpdater function cleanly encapsulates all the authentication, authorization, and data fetching logic. This separation makes the code more maintainable and testable.


18-24: Good authentication check

The authentication check is properly implemented early in the function, ensuring that unauthenticated users cannot proceed further.


57-72: Well-structured permission checking

The code clearly defines and checks for the three permission levels (global admin, organization admin, chat admin) that allow access to the updater information.


74-80: Efficient special case handling

The function efficiently handles special cases like null updaterId and when the updater is the current user, avoiding unnecessary database queries.


108-109: Clean implementation with the extracted function

The implementation is now much cleaner by using the extracted resolveUpdater function directly in the field definition.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
test/graphql/types/Chat/updater.test.ts (1)

145-145: 🧹 Nitpick (assertive)

Apply a consistent mocking pattern.
The code uses both mockImplementation(() => Promise.resolve(...)) in some places and mockResolvedValueOnce(...) in others. Use one approach consistently to align with your codebase's conventions and the retrieved learnings on mocking complex return types.

Also applies to: 185-185, 190-190, 192-192

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 313d6ae and c957a7b.

📒 Files selected for processing (2)
  • src/graphql/types/Chat/updater.ts (1 hunks)
  • test/graphql/types/Chat/updater.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
test/graphql/types/Chat/updater.test.ts (1)
Learnt from: yugal07
PR: PalisadoesFoundation/talawa-api#3253
File: test/graphql/types/Chat/updatedAt.test.ts:48-54
Timestamp: 2025-02-23T15:57:18.082Z
Learning: When mocking functions with specific return types in Vitest, prefer using `mockImplementation(() => Promise.resolve(value))` over `mockResolvedValue(value)` when dealing with complex types to ensure type safety.
⏰ Context from checks skipped due to timeout of 90000ms (1)
🔇 Additional comments (20)
test/graphql/types/Chat/updater.test.ts (12)

1-9: Good import organization and setup.
These imports are coherent with Vitest, Zod, and the application’s modules. The separation of type imports from the local modules is clear and helps readability.


11-26: Type definitions appear solid.
Defining these type aliases allows strong typing for user roles and membership roles, promoting clarity throughout the tests.


27-33: Mocked drizzle client structure is well-defined.
Ensuring it closely matches the actual shape of the drizzle client fosters consistency between test and production environments.


35-47: Mock data follows best practices.
Storing reusable data objects (like mockCurrentUser and mockUpdaterUser) at the top keeps the tests concise.


49-61: Parent object initialization is adequately detailed.
Providing explicit sample fields ensures the resolver can be tested thoroughly for multiple properties.


62-96: Context mocks are straightforward.
The authenticated and unauthenticated contexts are clearly distinguished, improving test coverage for both valid and invalid client states.


98-109: Effective unauthenticated checks.
Both the “unauthenticated user” and “unfound user” paths are well-tested, ensuring the resolver handles these invalid states gracefully.

Also applies to: 111-123


125-142: Unauthorized scenario is properly tested.
Verifying that regular users without admin privileges trigger an unauthorized action error covers critical permission checks.


144-159: Null updater scenario is tested carefully.
Confirming that a null updaterId returns null ensures robust handling of non-assigned updater references.


160-181: Current user as updater path is correctly handled.
This test confirms the correct return of the authenticated user when their ID matches the updaterId.


183-197: Consider consolidating similar test cases.
Testing “returns updater user when found” alongside subsequent tests for global/organization/chat admins produce overlapping flows examining user resolution. Combine or differentiate them more distinctly to reduce repetition.


199-225: Properly tests unexpected error scenario.
When the updater is referenced in the chat but not found in the database, the error handling is validated thoroughly, covering a potential data corruption case.

src/graphql/types/Chat/updater.ts (8)

13-24: Authentication check is clear.
Quickly throwing an unauthenticated error if the current client is not authenticated helps maintain security boundaries.


28-47: Fetching and joining membership data.
Using the with property in drizzleClient.query is an effective approach to gather chat and organization memberships in a single query, improving clarity of role checks.


49-55: Robust error for missing current user.
Throwing “unauthenticated” if the user is not found in the database closes loopholes for unauthorized access.


57-65: Variable extraction for membership roles is well-structured.
Separating isGlobalAdmin, isOrgAdmin, and isChatAdmin fosters readability, especially when applying multiple role checks.


66-72: Unauthorized users are handled correctly.
This ensures only users with admin privileges can access the updater, in accordance with the domain logic.


74-80: Return null or current user for special cases.
Skipping queries if updaterId is null or the same as currentUserId is a solid optimization, preventing unnecessary database lookups.


82-99: Detailed business logic error handling.
Logging the error message and throwing a distinct “unexpected” exception helps administrators diagnose data inconsistencies promptly.


104-112: Resolver mapping is straightforward.
Assigning resolve: resolveUpdater in the Chat type is clean and keeps the schema definition simple.

@yugal07
Copy link
Author

yugal07 commented Feb 27, 2025

@palisadoes, I have implemented all of the suggestions from coderabbit and added test cases for src/graphql/types/Chat/updater.ts as per your request. hence this PR now also solves issue #3058 . Let me know if theres need for more changes

@palisadoes palisadoes merged commit 38a7f65 into PalisadoesFoundation:develop-postgres Mar 1, 2025
16 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants