Skip to content

refactor: improve test structure with builder patterns and scenario templates #22635

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

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

anikdhabal
Copy link
Contributor

@anikdhabal anikdhabal commented Jul 18, 2025

refactor: improve test structure with builder patterns and scenario templates

Summary

This PR refactors Cal.com's unit test structure to reduce bloated and complex test setup by adopting builder patterns, factory functions, scenario templates, and standardized test utilities. The changes are additive and maintain backward compatibility - all existing tests continue to work unchanged.

Key improvements:

  • Builder patterns: Extended existing builders with buildBookingScenario, buildTestUser, buildMockRequestData providing sensible defaults
  • Scenario templates: Created createFreshBookingScenario, createRescheduleScenario, createTeamBookingScenario for common test patterns
  • Mock factories: Standardized calendar and video mocking with createStandardCalendarMock, createStandardVideoMock
  • Test helpers: High-level utilities like setupFreshBookingTest that combine setup, mocking, and expectations

Before/After comparison:

// Before: 50+ lines of repetitive setup
const booker = getBooker({ email: "booker@example.com", name: "Booker" });
const organizer = getOrganizer({
  name: "Organizer", email: "organizer@example.com", id: 101,
  schedules: [TestData.schedules.IstWorkHours],
  credentials: [getGoogleCalendarCredential()],
  // ... 40+ more lines
});

// After: 3 lines with sensible defaults
const { mocks, mockRequestData, organizer, booker } = await setupFreshBookingTest({
  withWebhooks: true, withWorkflows: true,
});

Review & Testing Checklist for Human

  • Verify test behavior preservation: Run the example refactored test and compare results with equivalent traditional test setup to ensure identical behavior
  • Test builder pattern flexibility: Try various combinations of overrides in the new helper functions to ensure they work correctly with edge cases
  • Check type safety: Review the TypeScript type definitions and casting decisions, particularly around organizer/booker types and Record<string, unknown> usage
  • Integration testing: Verify the new utilities integrate properly with existing test infrastructure (getOrganizer, createBookingScenario, etc.)
  • Regression testing: Run existing booking tests to ensure no functionality is broken by the new utilities

Recommended test plan:

  1. Run TZ=UTC yarn test apps/web/test/utils/bookingScenario/examples/refactoredFreshBooking.test.ts
  2. Compare with running an equivalent traditional booking test
  3. Try creating a new test using the new patterns with various override combinations
  4. Run a broader test suite to check for regressions

Diagram

%%{ init : { "theme" : "default" }}%%
graph TD
    Builder["packages/lib/test/builder.ts<br/>buildBookingScenario<br/>buildTestUser<br/>buildMockRequestData"]:::major-edit
    
    ScenarioTemplates["apps/web/test/utils/bookingScenario/<br/>scenarioTemplates.ts<br/>createFreshBookingScenario<br/>createRescheduleScenario"]:::major-edit
    
    MockFactories["apps/web/test/utils/bookingScenario/<br/>mockFactories.ts<br/>createStandardCalendarMock<br/>createStandardVideoMock"]:::major-edit
    
    TestHelpers["apps/web/test/utils/bookingScenario/<br/>testHelpers.ts<br/>setupFreshBookingTest<br/>expectStandardBookingSuccess"]:::major-edit
    
    ExampleTest["apps/web/test/utils/bookingScenario/<br/>examples/refactoredFreshBooking.test.ts"]:::major-edit
    
    ExistingBookingScenario["apps/web/test/utils/bookingScenario/<br/>bookingScenario.ts<br/>getOrganizer, getScenarioData"]:::context
    
    ExistingExpects["apps/web/test/utils/bookingScenario/<br/>expects.ts<br/>expectBookingToBeInDatabase"]:::context

    Builder --> ScenarioTemplates
    ScenarioTemplates --> TestHelpers
    MockFactories --> TestHelpers
    TestHelpers --> ExampleTest
    ExistingBookingScenario --> ScenarioTemplates
    ExistingExpects --> TestHelpers
    
    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

  • Backward compatibility: All existing test utilities remain unchanged and functional
  • Type safety: Used Record<string, unknown> instead of any and explicit type casting where needed
  • Testing: All new utilities pass type checking and the example test demonstrates equivalent behavior
  • Documentation: Created comprehensive examples showing before/after patterns

Session details: Requested by @anikdhabal
Devin session: https://app.devin.ai/sessions/bc4f255018b6475d95d66fce4243008a

…emplates

- Extend existing builders with sensible defaults and new utilities
- Create scenario templates for common test patterns (fresh, reschedule, team)
- Add standardized mock factories to reduce repetitive setup code
- Provide high-level test helpers that combine setup, mocking, and expectations
- Maintain backward compatibility with existing test utilities
- Add comprehensive documentation and examples
- Fix lint issues by replacing any types with proper type annotations

The refactoring reduces test setup from 50+ lines to 3 lines while preserving
exact test behavior and coverage. All existing tests continue to work unchanged.

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

vercel bot commented Jul 18, 2025

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

2 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
cal ⬜️ Ignored Aug 12, 2025 4:55pm
cal-eu ⬜️ Ignored Aug 12, 2025 4:55pm

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 18, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch devin/1752864512-refactor-test-structure

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 18, 2025
Copy link

delve-auditor bot commented Jul 18, 2025

No security or compliance issues detected. Reviewed everything up to f3942f4.

Security Overview
  • 🔎 Scanned files: 8 changed file(s)
Detected Code Changes
Change Type Relevant files
Enhancement ► bookingScenario/
    Added test utilities and helper functions
► testHelpers.ts
    Added test helper functions and builders
► builder.ts
    Added scenario builders and test data generators
Refactor ► UserListTable.tsx
    Simplified column configuration
► credit-service.test.ts
    Removed redundant test case
Configuration changes ► package.json
    Updated version number
► recommended.ts
    Updated ESLint configuration

Reply to this PR with @delve-auditor followed by a description of what change you want and we'll auto-submit a change to this PR to implement it.

- Fix organizer type to include required timeZone property
- Cast rescheduleUid to string type in mock factories
- Update type definitions for better type safety
- Ensure all test helper functions return properly typed objects

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
devin-ai-integration bot and others added 2 commits August 12, 2025 16:53
- Create complementary architecture between foundation and convenience layers
- Foundation layer (packages/lib/test/testHelpers.ts): Advanced builder classes and low-level utilities
- Convenience layer (apps/web/test/utils/bookingScenario/testHelpers.ts): Beginner-friendly setup functions
- Update booking scenario helpers to use foundation utilities via createBookingMocks
- Add comprehensive README.md documentation explaining when to use each approach
- Support for seated events, round-robin, and recurring event scenarios
- Maintain backward compatibility with all existing tests
- Fix type checking issues and method access problems

This provides both simplicity for beginners (90% of cases) and flexibility for advanced users (10% of cases).

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
- Move README.md from apps/web/test/utils/bookingScenario/ to packages/lib/test/
- Centralizes documentation for both testHelpers files in foundation layer location
- Makes test utility guide more discoverable for all developers
- No functional changes, just improved organization

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
core area: core, team members only
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants