author avatar

aman.suhag

Wed Sep 25 2024

Sending Body Data as json:
The json function in the request is simulating the body of the request. In a real-world scenario, when you send a request with data (like when you're submitting a form or sending some payload), it is typically part of the body of the HTTP request.
In your test case:


json: async () => ({
  standupData,
}),


This simulates the request body. Since you're testing a PATCH method (which is often used to update resources), the server expects some data to update the resource. This json function acts like a mock for what would be req.body in a real request. In your API handler, you'd probably be extracting the body data using something like:


const data = await req.json();


Thus, the test needs to mock this body data to simulate a real request. It's done asynchronously here because in actual implementations, reading the body data is often asynchronous (e.g., when streaming).
Passing Context (with params):
The context object typically holds parameters that are passed via the route in a Next.js API request, especially when using dynamic routes (e.g., /api/standups/[id]/toggle-status). In Next.js, when you define a dynamic API route like /api/standups/[id]/toggle-status, the id is part of the route path, and Next.js passes it in the context.params object.
In your test case:


const context = {
  params: {
    id: standup.id,
  },
};


You're simulating the dynamic parameter id as part of the request. This is necessary because your API handler likely expects id to come from the route context (not just from the query string or body). In the handler, you're accessing context.params.id:


const { id } = context.params as { id: string };


This allows your API handler to know which standup you're targeting for the update.
#app-router #dynamic-routes #json