Skip to content

test: add comprehensive unit tests for handleInstantMeeting #22820

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 20 commits into from
Jul 31, 2025

Conversation

anikdhabal
Copy link
Contributor

@anikdhabal anikdhabal commented Jul 30, 2025

test: add comprehensive unit tests for handleInstantMeeting

Summary

This PR reverts all previous changes related to the username constraint violation fix and instead adds comprehensive unit tests for the handleInstantMeeting function located at packages/features/instant-meeting/handleInstantMeeting.ts.

Key Changes:

  • Added: New comprehensive unit test file packages/features/instant-meeting/handleInstantMeeting.test.ts
  • Unchanged: The handleInstantMeeting.ts implementation itself remains untouched

The new test suite covers:

  • Team event type validation (non-team events should throw error)
  • Successful instant meeting creation for team events
  • Booking creation with AWAITING_HOST status
  • Integration with Cal Video meeting creation
  • Attendee and booking data processing

Review & Testing Checklist for Human

  • 🚨 CRITICAL: Fix translation mocking issue - Tests are currently failing with "tAttendees is not a function" error. The getTranslation mock may need adjustment or the handleInstantMeeting.ts code may need modification to remove translation dependency.
  • Verify test coverage completeness - Review if the test cases cover all important scenarios for handleInstantMeeting (error cases, edge cases, webhook triggers, browser notifications)
  • Test the actual functionality end-to-end - Since unit tests are failing, manually test instant meeting creation to ensure the functionality works correctly
  • Review mocking strategy - Ensure the minimal mocking approach follows existing patterns and adequately isolates the function under test

Recommended test plan:

  1. Fix the failing unit tests first
  2. Run the tests locally with TZ=UTC yarn test packages/features/instant-meeting/handleInstantMeeting.test.ts
  3. Manually test instant meeting creation in the UI to verify end-to-end functionality
  4. Verify that removing previous username constraint changes didn't break anything

Diagram

%%{ init : { "theme" : "default" }}%%
graph TD
    subgraph "Test Files"
        A["packages/features/instant-meeting/<br/>handleInstantMeeting.test.ts"]:::major-edit
        B["packages/trpc/server/routers/viewer/teams/<br/>removeMember.test.ts"]:::minor-edit
    end
    
    subgraph "Implementation Files"
        C["packages/features/instant-meeting/<br/>handleInstantMeeting.ts"]:::context
        D["packages/features/ee/teams/lib/<br/>removeMember.ts"]:::minor-edit
    end
    
    subgraph "Test Dependencies"
        E["@calcom/web/test/utils/bookingScenario/<br/>bookingScenario.ts"]:::context
        F["tests/libs/__mocks__/prisma"]:::context
    end
    
    A -->|"tests"| C
    A -->|"uses"| E
    A -->|"uses"| F
    B -->|"reverted to original"| D
    
    subgraph Legend
        L1["Major Edit"]:::major-edit
        L2["Minor Edit"]:::minor-edit  
        L3["Context/No Edit"]:::context
    end

classDef major-edit fill:#90EE90
classDef minor-edit fill:#87CEEB  
classDef context fill:#FFFFFF
Loading

Notes

  • Translation Issue: The tests are currently failing due to a translation mocking problem. The getTranslation function returns a function that should be called with translation keys, but the mock may not be returning the correct structure.
  • Scope Change: This PR completely changed scope from fixing a username constraint violation to adding unit tests. The username constraint issue will be addressed separately.
  • Testing Pattern: The new tests follow the fresh-booking.test.ts pattern with minimal mocking and integration testing approach using prismock.

Link to Devin run: https://app.devin.ai/sessions/12f0c4070a404750aaaee19477da6c32
Requested by: @anikdhabal (anik@cal.com)

- Update username to - format when removing users from organizations
- Fix unique constraint violation on (username, organizationId) when organizationId is null
- Add test case to verify username format change and successful removal
- Fix skipped test by adding proper imports and removing describe.skip

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
Copy link
Contributor

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR that start with 'DevinAI'.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment and CI monitoring

Copy link
Contributor

coderabbitai bot commented Jul 30, 2025

Walkthrough

A new test file, handleInstantMeeting.test.ts, has been introduced to test the handleInstantMeeting API handler. The test suite uses Vitest and includes comprehensive tests that mock dependencies such as Prisma, notification sending, and video meeting creation. The tests cover scenarios for creating instant meetings for team event types, verifying correct booking data, attendee handling, status assignment, and meeting token management. The suite also includes tests to ensure proper error handling when non-team event types are used. Utility functions and mocks are employed to simulate related behaviors and isolate the handler logic.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch devin/fix-username-constraint-removemember-1753884495

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests 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.

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.

@keithwillcode keithwillcode added the core area: core, team members only label Jul 30, 2025
- Create two users with same username (one with null orgId, one with orgId)
- Verify removing org user updates username without unique constraint error
- Test ensures username gets updated to - format

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
Copy link

vercel bot commented Jul 30, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
cal ⬜️ Ignored (Inspect) Jul 31, 2025 10:13am
cal-eu ⬜️ Ignored (Inspect) Jul 31, 2025 10:13am

@anikdhabal anikdhabal marked this pull request as ready for review July 30, 2025 14:53
@graphite-app graphite-app bot requested a review from a team July 30, 2025 14:53
Copy link

graphite-app bot commented Jul 30, 2025

Graphite Automations

"Add consumer team as reviewer" took an action on this PR • (07/30/25)

1 reviewer was added to this PR based on Keith Williams's automation.

"Add ready-for-e2e label" took an action on this PR • (07/31/25)

1 label was added to this PR based on Keith Williams's automation.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4489cb8 and 6121a2a.

📒 Files selected for processing (2)
  • packages/features/ee/teams/lib/removeMember.ts (1 hunks)
  • packages/trpc/server/routers/viewer/teams/removeMember.test.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/trpc/server/routers/viewer/teams/removeMember.test.ts
  • packages/features/ee/teams/lib/removeMember.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/trpc/server/routers/viewer/teams/removeMember.test.ts
  • packages/features/ee/teams/lib/removeMember.ts
🔇 Additional comments (2)
packages/trpc/server/routers/viewer/teams/removeMember.test.ts (2)

3-10: LGTM! Comprehensive test utilities imported.

The imported test utilities are appropriate and necessary for creating the comprehensive test scenario that validates the username constraint fix.


173-283: Excellent test coverage for the constraint violation fix!

This test comprehensively validates the core issue described in the PR objectives. It creates the exact scenario that would cause the unique constraint violation (two users with identical usernames, one with null organizationId) and verifies:

  1. The removal operation completes without throwing an exception
  2. The removed user's username is correctly updated to include their ID
  3. The other user's data remains unchanged

The test structure follows best practices and provides strong confidence in the fix.

@dosubot dosubot bot added automated-tests area: unit tests, e2e tests, playwright 🐛 bug Something isn't working labels Jul 30, 2025
@anikdhabal anikdhabal enabled auto-merge (squash) July 30, 2025 15:56
@anikdhabal anikdhabal marked this pull request as draft July 30, 2025 16:32
auto-merge was automatically disabled July 30, 2025 16:32

Pull request was converted to draft

- Revert previous removeMember changes
- Add full test coverage for instant meeting functionality
- Test team validation, booking creation, token generation
- Test webhook triggers and browser notifications
- Mock external dependencies for isolated unit tests
- Translation issue to be addressed in future iteration

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
@devin-ai-integration devin-ai-integration bot changed the title fix: resolve username constraint violation in removeMember test: add comprehensive unit tests for handleInstantMeeting Jul 31, 2025
anikdhabal and others added 8 commits July 31, 2025 15:00
* encode redirect url to make sure it has all parameters

* add changesets
…eld` (#22740)

* Passing tests and fixed

* self review addressed adn more tests
* fix: Adjacency issue when working hours connect over multiple days

* Add tests to validate the new merging of day end logic

* Update to correct annotation.

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Implement subsequent date ranges for date overrides also

* The map needs to be updated on successful resolve.

* test: add failing test for overlapping ranges with same end time

Demonstrates bug where overlapping working hour ranges (6:00-10:00 and 8:00-10:00)
lose the earlier portion (6:00-8:00), showing only 8:00 and 9:00 slots
instead of all 4 slots (6:00, 7:00, 8:00, 9:00).

Related to Carina's comment on PR #21912.

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: properly merge overlapping ranges with same end time

Fixes bug where overlapping working hour ranges with the same end time
(e.g., 6:00-10:00 and 8:00-10:00) would lose the earlier portion of the
first range. The merging logic now correctly preserves the earliest
start time when ranges overlap and share the same end time.

This ensures all expected time slots are available (6:00, 7:00, 8:00, 9:00)
instead of losing the earlier slots (6:00, 7:00).

Resolves the issue identified in Carina's comment on PR #21912.

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* perf: optimize overlapping range detection from O(n²) to O(n)

Replaces Object.keys().find() with Map-based lookup for ranges with same end time.
This optimization handles 2000+ date ranges efficiently, reducing complexity from
4M operations to linear time while maintaining the same merging behavior.

Performance improvement for high-volume event types with many availability ranges.

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* remove first weeks and add last

* fix added last week

* prefetch availability of next month

* don't switch month

* On hover show month

* only show new UI in monthly view

* show month tooldtip only when needed

* show month on first day of month

* remove isFirstDayOfNextMonth

* fix prefetching next month

* fix datePicker tests

* preventMonthSwitching in monthly view

* add tests

* code clean up

* code clean up

* code clena up for ooo days

* push first day of month

* remove bg color for the month badge

* fix text colour

* remove not needed

* use object param

* revert: use object param

* use object param

* fix DatePicker tests

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Sean Brydon <sean@cal.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
* Refactor logs

* Add specific info to log
* Automatically enable migration of a team that conflicts with Orgs slug

* Allow changing the orgs slug and name if user goes back and changes it

* avoid crashing on some scenarios

* Revert "Allow changing the orgs slug and name if user goes back and changes it"

This reverts commit f8872b0.

* fix: handle unpublished teams gracefully in org migration

- Change 'No oldSlug for team' from error to warning for unpublished teams
- Keep 'No slug for team' as error since org onboarding ensures teams have names
- Add test for migrating unpublished teams without oldSlug
- Add clarifying comments about when each condition can occur
sean-brydon and others added 5 commits July 31, 2025 09:34
… injection (#22768)

* refactor: convert checkBookingLimits to class service with dependency injection

- Create CheckBookingLimitsService class following AvailableSlotsService pattern
- Add countBookingsByEventTypeAndDateRange method to BookingRepository
- Move direct prisma calls from service to repository layer
- Implement dependency injection with proper DI tokens and modules
- Update all usage points to use the new service through DI
- Maintain backward compatibility with error-throwing wrapper functions
- Update tests to use the new service pattern
- Resolve TODO comment in AvailableSlotsService for DI integration

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: DI CheckBookingLimitsService in v2 slots service

* chore: bump libraries

* chore: create getCheckBookingLimitsService

* refactor: convert checkBookingAndDurationLimits to service class with DI

- Create CheckBookingAndDurationLimitsService class following DI pattern
- Add DI tokens and module for the new service
- Update booking-limits container to provide the new service
- Refactor handleNewBooking.ts to use service through DI
- Maintain backward compatibility with deprecated function export
- Preserve all existing functionality while improving code organization

Co-Authored-By: morgan@cal.com <morgan@cal.com>

* chore: CheckBookingAndDurationLimitsService

* chore: bump platform libs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: morgan@cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
* Return a busy block placeholder if calendar throws an error

* Refactor `getCalendarsEvents` to return an object with a success prop

* Throw error in `getBusyTimes` if failed to fetch calendar availability

* Return empty available days if error getting busy times

* yeet.

* Type fix

* Fix type error in getLuckyUsers

* Type fixes

* Type fix

* Type fix

* Fix test

* Fix test mocks

* Refactor calendars.service to use new calendarBusyTimesQuery

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
…mocking

- Add setupAndTeardown() for proper test environment setup
- Use mockNoTranslations() to fix translation function mocking
- Simplify NextApiRequest mock to resolve TypeScript errors
- Both test cases now pass successfully

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
@github-actions github-actions bot added the ❗️ migrations contains migration files label Jul 31, 2025
@anikdhabal anikdhabal removed the ❗️ migrations contains migration files label Jul 31, 2025
@anikdhabal anikdhabal marked this pull request as ready for review July 31, 2025 10:14
@anikdhabal anikdhabal enabled auto-merge (squash) July 31, 2025 10:14
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

🧹 Nitpick comments (1)
packages/features/instant-meeting/handleInstantMeeting.test.ts (1)

195-203: Consider using the existing getDate utility to reduce code duplication.

The local getDate function duplicates functionality available in the imported bookingScenario utilities. The existing utility function provides more comprehensive date handling with proper overflow management.

Consider removing the local function and using the imported one:

- function getDate(param: { dateIncrement?: number } = {}) {
-   const { dateIncrement = 0 } = param;
-   const date = new Date();
-   date.setDate(date.getDate() + dateIncrement);
-   return {
-     date,
-     dateString: date.toISOString().split("T")[0],
-   };
- }

And update the usage (lines 48, 143) to use the imported function:

- const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });
+ const { dateString: plus1DateString } = getDate({ dateIncrement: 1 });

The imported getDate already returns a dateString property, so the usage would remain the same.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6121a2a and aed4bf8.

📒 Files selected for processing (1)
  • packages/features/instant-meeting/handleInstantMeeting.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

**/*.ts: For Prisma queries, only select data you need; never use include, always use select
Ensure the credential.key field is never returned from tRPC endpoints or APIs

Files:

  • packages/features/instant-meeting/handleInstantMeeting.test.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/review.mdc)

Flag excessive Day.js use in performance-critical code; prefer native Date or Day.js .utc() in hot paths like loops

Files:

  • packages/features/instant-meeting/handleInstantMeeting.test.ts
🧠 Learnings (2)
📓 Common learnings
Learnt from: vijayraghav-io
PR: calcom/cal.com#21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.
packages/features/instant-meeting/handleInstantMeeting.test.ts (1)

Learnt from: vijayraghav-io
PR: #21072
File: packages/app-store/office365calendar/api/webhook.ts:120-123
Timestamp: 2025-07-18T17:57:16.395Z
Learning: The office365calendar webhook handler in packages/app-store/office365calendar/api/webhook.ts is specifically designed for Office365 calendar integration, not as a generic webhook handler. Therefore, it's safe to assume that fetchAvailabilityAndSetCache method will be implemented in the Office365CalendarService, making explicit validation checks unnecessary.

🧬 Code Graph Analysis (1)
packages/features/instant-meeting/handleInstantMeeting.test.ts (1)
apps/web/test/utils/bookingScenario/bookingScenario.ts (9)
  • mockNoTranslations (1630-1638)
  • getOrganizer (1474-1530)
  • TestData (1193-1465)
  • getGoogleCalendarCredential (1146-1154)
  • getDate (1047-1094)
  • createBookingScenario (932-963)
  • getScenarioData (1532-1618)
  • mockSuccessfulVideoMeetingCreation (2000-2018)
  • mockCalendarToHaveNoBusySlots (1879-1892)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Install dependencies / Yarn install & cache
🔇 Additional comments (4)
packages/features/instant-meeting/handleInstantMeeting.test.ts (4)

1-18: LGTM! Well-structured imports following established patterns.

The import structure is clean and follows the established pattern used in other Cal.com test files, importing necessary testing utilities and dependencies.


19-31: LGTM! Proper dependency mocking for unit testing.

The mocks appropriately isolate external dependencies (notifications and video client) while providing realistic mock data for testing the core functionality.


37-131: Excellent comprehensive test coverage for successful instant meeting creation.

The test thoroughly covers the happy path scenario:

  • Proper test data setup using established utilities
  • Appropriate mocking of external dependencies
  • Comprehensive assertions validating both API response and database state
  • Realistic request data structure

The test follows established patterns and provides good coverage of the instant meeting creation functionality.


132-192: LGTM! Proper error handling test for business rule validation.

The test effectively validates that the handler correctly enforces the business rule that only team event types support instant meetings. The test structure mirrors the success case but omits the team property, ensuring the error path is properly tested.

Copy link
Contributor

E2E results are ready!

@anikdhabal anikdhabal merged commit 2cc7827 into main Jul 31, 2025
60 of 65 checks passed
@anikdhabal anikdhabal deleted the devin/fix-username-constraint-removemember-1753884495 branch July 31, 2025 10:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
automated-tests area: unit tests, e2e tests, playwright 🐛 bug Something isn't working core area: core, team members only ready-for-e2e
Projects
None yet
Development

Successfully merging this pull request may close these issues.

9 participants