Skip to content

Setup MSW for API mocking during development and testing#51

Merged
iamitprakash merged 7 commits intoRealDevSquad:developfrom
Hariom01010:setup-msw
Jul 22, 2025
Merged

Setup MSW for API mocking during development and testing#51
iamitprakash merged 7 commits intoRealDevSquad:developfrom
Hariom01010:setup-msw

Conversation

@Hariom01010
Copy link
Contributor

@Hariom01010 Hariom01010 commented Jul 4, 2025

Date: 05 Jul 2025

Developer Name: @Hariom01010


Issue Ticket Number

Closes #49

Description

This PR introduces MSW setup to enable API mocking during development and testing phases.

  • Separate functions have been introduced to use setupWorker (for client side mocking like CSR components) and setupServer (for server side mocking for SSR components)
  • Environment variables are used to conditionally enable or disable API mocking

Documentation Updated?

  • Yes
  • No

Under Feature Flag

  • Yes
  • No

Database Changes

  • Yes
  • No

Breaking Changes

  • Yes
  • No

Development Tested?

  • Yes
  • No

Screenshots

Screenshot 1

When mocking is disabled:

image

When mocking is enabled:

image

Test Coverage

Screenshot 1 image

Additional Notes

Description by Korbit AI

What change is being made?

Integrate Mock Service Worker (MSW) for API mocking during development and testing by setting up service worker scripts, adding application configuration settings, and employing relevant providers and modules.

Why are these changes being made?

The changes aim to enhance development and testing efficiency by allowing local API mocking, which circumvents the need for actual server communication and enables testing with predetermined server responses. This setup facilitates robust development workflows and simplifies testing by providing control over API interactions. By only activating mocks when the app is in development mode and isMockingEnabled, we ensure that production deployments aren't affected.

Is this description stale? Ask me to generate a new description by commenting /korbit-generate-pr-description

@coderabbitai
Copy link

coderabbitai bot commented Jul 4, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

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.

Summary by CodeRabbit

  • New Features

    • Introduced robust API mocking capabilities for task management, including support for GET, POST, PATCH, and DELETE operations on tasks.
    • Added a comprehensive set of mock task data and types to simulate realistic task scenarios during development.
    • Integrated a Mock Service Worker (MSW) setup for both browser and server environments, enabling seamless API request interception.
  • Chores

    • Added the MSW library as a development dependency and configured the service worker for local development.
    • Updated application layout to ensure all components operate within the mock environment when enabled.
  • Refactor

    • Removed outdated mock data to streamline and standardize the mocking setup.

Walkthrough

The codebase introduces Mock Service Worker (MSW) integration for API mocking in development and testing. It adds mock data, handlers for task-related API endpoints, utility functions, type definitions, and conditional initialization logic for both browser and server environments. The app layout is updated to include an MSW provider, and the MSW worker script is added.

Changes

File(s) Change Summary
__mocks__/Task.ts Deleted legacy mock task data file.
__mocks__/db/tasks.ts, __mocks__/types.ts Added comprehensive mock task dataset and related TypeScript type definitions.
__mocks__/utils/generateObjectId.ts Added utility for generating MongoDB-like ObjectIds.
__mocks__/handlers/tasks.handler.ts, __mocks__/handlers/index.ts Added MSW handlers for GET, POST, PATCH, DELETE /v1/tasks endpoints and handler aggregator.
__mocks__/browser.ts, __mocks__/server.ts Added MSW setup for browser (worker) and server (node) environments.
__mocks__/enableMockServer.ts Added function to conditionally enable server-side API mocking.
app/msw-provider.tsx Added React provider component to initialize MSW in the browser during development.
app/layout.tsx Integrated MSW provider and enabled server mocking in the app's root layout.
package.json Added msw as a dev dependency and configured worker directory.
public/mockServiceWorker.js Added MSW service worker script for intercepting network requests in the browser.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant MSWProvider
    participant MSW Worker/Server
    participant Handlers

    User->>App: Loads application
    App->>MSWProvider: Render children
    MSWProvider->>MSW Worker/Server: Initialize if in dev & mocking enabled
    App->>API: Makes /v1/tasks request
    API->>MSW Worker/Server: Intercept request
    MSW Worker/Server->>Handlers: Route to appropriate handler (GET/POST/PATCH/DELETE)
    Handlers->>MSW Worker/Server: Return mock response
    MSW Worker/Server->>API: Respond with mock data
    API->>App: Receives mock data
    App->>User: Displays tasks using mock data
Loading

Assessment against linked issues

Objective Addressed Explanation
Integrate MSW to intercept API calls and return predefined data in development and testing (#49)
Provide mock data for task lists, creation responses, and support toggling between real and mock APIs via environment variable (#49)
Ensure MSW setup for both browser and server environments, with conditional initialization (#49)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Poem

In the land of code where rabbits dwell,
Mocked APIs now work so well!
With MSW's gentle, magic hand,
Tasks appear just as we planned.
No backend woes, no waiting queue—
The frontend hops with data new!
🐇✨


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

Copy link

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Performance Unconditional MSW Provider Wrapper ▹ view
Functionality Unconditional MSW Initialization ▹ view
Logging Insufficient context in unhandled request warning ▹ view ✅ Fix detected
Readability Complex conditional statement ▹ view ✅ Fix detected
Functionality Invalid MongoDB ObjectId Format Generation ▹ view
Readability Unexplained Timestamp Conversion Constants ▹ view ✅ Fix detected
Logging Inappropriate logging method for MSW initialization ▹ view ✅ Fix detected
Performance Missing Import Preload ▹ view
Performance Inefficient String Generation Method ▹ view ✅ Fix detected
Readability Unclear request handling logic ▹ view
Files scanned
File Path Reviewed
mocks/handlers/index.ts
mocks/server.ts
mocks/browser.ts
mocks/utils/generateObjectId.ts
mocks/enableMockServer.ts
app/layout.tsx
app/msw-provider.tsx
mocks/types.ts
public/mockServiceWorker.js
mocks/handlers/tasks.handler.ts
mocks/db/tasks.ts

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between db0c0f6 and 7d0bf93.

📒 Files selected for processing (13)
  • __mocks__/Task.ts (0 hunks)
  • __mocks__/browser.ts (1 hunks)
  • __mocks__/db/tasks.ts (1 hunks)
  • __mocks__/enableMockServer.ts (1 hunks)
  • __mocks__/handlers/index.ts (1 hunks)
  • __mocks__/handlers/tasks.handler.ts (1 hunks)
  • __mocks__/server.ts (1 hunks)
  • __mocks__/types.ts (1 hunks)
  • __mocks__/utils/generateObjectId.ts (1 hunks)
  • app/layout.tsx (2 hunks)
  • app/msw-provider.tsx (1 hunks)
  • package.json (2 hunks)
  • public/mockServiceWorker.js (1 hunks)
💤 Files with no reviewable changes (1)
  • mocks/Task.ts
🧰 Additional context used
🧬 Code Graph Analysis (8)
__mocks__/browser.ts (1)
__mocks__/handlers/index.ts (1)
  • handlers (3-3)
__mocks__/server.ts (1)
__mocks__/handlers/index.ts (1)
  • handlers (3-3)
__mocks__/handlers/index.ts (1)
__mocks__/handlers/tasks.handler.ts (1)
  • taskHandlers (325-325)
app/layout.tsx (2)
__mocks__/enableMockServer.ts (1)
  • enableServerMocking (1-7)
app/msw-provider.tsx (1)
  • MSWProvider (28-36)
__mocks__/enableMockServer.ts (1)
__mocks__/server.ts (1)
  • server (4-4)
__mocks__/db/tasks.ts (1)
__mocks__/types.ts (1)
  • Task (1-39)
app/msw-provider.tsx (1)
__mocks__/browser.ts (1)
  • worker (4-4)
__mocks__/handlers/tasks.handler.ts (3)
__mocks__/db/tasks.ts (1)
  • tasksData (3-540)
__mocks__/types.ts (2)
  • CreateTaskPayload (65-73)
  • UpdateTaskPayload (75-89)
__mocks__/utils/generateObjectId.ts (1)
  • generateObjectId (1-7)
🪛 Biome (1.9.4)
public/mockServiceWorker.js

[error] 288-288: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (14)
package.json (1)

62-66: LGTM! MSW configuration is correctly structured.

The MSW configuration with workerDirectory: ["public"] follows the standard setup pattern for Next.js applications.

__mocks__/handlers/index.ts (1)

1-3: LGTM! Clean handler aggregation pattern.

The handler aggregation approach provides good organization and scalability for managing multiple handler modules.

__mocks__/browser.ts (1)

1-4: LGTM! Standard MSW browser setup.

The implementation follows the correct pattern for browser-side MSW setup with proper imports and worker configuration.

__mocks__/server.ts (1)

1-4: LGTM! Standard MSW server setup.

The implementation follows the correct pattern for server-side MSW setup, complementing the browser setup for comprehensive mocking coverage.

__mocks__/utils/generateObjectId.ts (1)

1-7: LGTM! Correct ObjectId generation implementation.

The function correctly generates MongoDB-compatible ObjectIds with:

  • 8-character timestamp (Unix timestamp in hex)
  • 16-character random hex string
  • Total 24 characters matching MongoDB ObjectId format

The implementation is mathematically sound and appropriate for mock data generation.

app/layout.tsx (2)

4-7: Well-structured MSW integration!

The integration properly enables both server-side and client-side mocking by calling enableServerMocking() at the top level and wrapping the app with MSWProvider. This follows MSW best practices for Next.js applications.


29-31: Proper MSW provider setup in the component tree.

The MSWProvider correctly wraps the children in the body element, ensuring all components have access to the mocking context on the client side.

__mocks__/db/tasks.ts (1)

3-540: Well-structured mock data with comprehensive coverage.

The mock data provides excellent coverage of different task scenarios with varied priorities, statuses, assignees, and labels. The data structure is consistent and realistic for testing purposes.

app/msw-provider.tsx (2)

4-17: Excellent MSW worker setup with proper browser detection.

The conditional promise setup properly checks for browser environment, development mode, and API mocking flag. The worker configuration correctly ignores Next.js internal requests and provides appropriate warnings for unhandled requests.


28-36: Well-implemented React Suspense pattern for async MSW initialization.

The MSWProvider uses Suspense correctly to handle the asynchronous worker initialization, ensuring the MSW worker is ready before rendering children.

__mocks__/types.ts (1)

1-39: Comprehensive Task type definition with detailed structure.

The Task type provides excellent coverage of all task-related fields including complex nested objects for assignees, labels, and deferred details. The structure supports comprehensive task management functionality.

__mocks__/handlers/tasks.handler.ts (2)

8-79: Clean pagination implementation with proper validation!

The GET handler correctly validates query parameters, implements pagination with sensible defaults, and provides comprehensive error responses.


264-323: Well-implemented DELETE handler following REST conventions!

Correctly returns 204 No Content on successful deletion and provides appropriate error responses.

public/mockServiceWorker.js (1)

1-345: Auto-generated MSW service worker file - no modifications needed.

This file is automatically generated by MSW and should not be modified as stated in the header comments. Any updates should be done through MSW's initialization commands.

@Hariom01010 Hariom01010 force-pushed the setup-msw branch 3 times, most recently from d070ced to 7fc8090 Compare July 6, 2025 11:10
@Hariom01010 Hariom01010 self-assigned this Jul 6, 2025
@Hariom01010 Hariom01010 added the DX Improving the developer experience label Jul 6, 2025
@Hariom01010 Hariom01010 requested a review from AnujChhikara July 10, 2025 10:57
@Hariom01010 Hariom01010 marked this pull request as draft July 16, 2025 13:33
@Hariom01010 Hariom01010 marked this pull request as ready for review July 17, 2025 22:50
Copy link

@korbit-ai korbit-ai bot left a comment

Choose a reason for hiding this comment

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

Review by Korbit AI

Korbit automatically attempts to detect when you fix issues in new commits.
Category Issue Status
Documentation Insufficient Header Documentation Context ▹ view
Performance Excessive Response/Request Cloning ▹ view
Functionality Empty MSW Handlers Array ▹ view
Functionality Unconditional MSW Initialization ▹ view
Readability Use async/await over promise chains ▹ view
Readability Avoid acronyms in component names ▹ view ✅ Fix detected
Error Handling Silent Mocking Initialization Failure ▹ view ✅ Fix detected
Files scanned
File Path Reviewed
mocks/handlers/index.ts
mocks/server.ts
mocks/browser.ts
components/msw-provider.tsx
app/layout.tsx
mocks/init.ts
components/providers.tsx
public/mockServiceWorker.js

Explore our documentation to understand the languages and file types we support and the files we ignore.

Check out our docs on how you can make Korbit work best for you and your team.

Loving Korbit!? Share us on LinkedIn Reddit and X

disabled
- renamed MSWProvider to MockServiceWorkerProvider for better context
- update condition to consolve mocking is disable message only when app
  is running in dev
@Hariom01010 Hariom01010 requested a review from AnujChhikara July 20, 2025 23:57
@iamitprakash iamitprakash merged commit e51f87e into RealDevSquad:develop Jul 22, 2025
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 16, 2025
10 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

DX Improving the developer experience

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[DX] Integrate MSW to Intercept API calls and return predefined data in development and testing

6 participants