Skip to content

Instantly share code, notes, and snippets.

@william-murphy
Created October 4, 2023 13:11
Show Gist options
  • Save william-murphy/01c6e597fc0df7f27df7c020635fdfac to your computer and use it in GitHub Desktop.
Save william-murphy/01c6e597fc0df7f27df7c020635fdfac to your computer and use it in GitHub Desktop.
// ~/tests/api/thing.test.ts
import 'isomorphic-fetch' // because otherwise NextRequest and NextResponse aren't defined??
import { createRequest, createResponse } from "node-mocks-http"
import { GET, POST } from "~/app/api/thing/route"
import type { Thing } from "~/types/thing"
descrive("/api/thing", () => {
test("creates a new thing with valid data", async () => {
const thing: Thing = {
title: "test title",
purpose: "test purpose"
}
const req = createRequest({
method: "POST",
url: "/api/thing",
headers: {
"Content-Type": "application/json"
},
body: thing
}
const res = await POST(req) // at this point it goes to the route handler function, never to return...
// the rest of the code
})
})
// ~/app/api/thing/route.ts
import { NextRequest, NextResponse } from "next/server"
export async function POST(request: NextRequest) {
const { title, purpose } = await request.json()
// at this point (line 33) it errors with request.json is not a function, however, when I test the routes manually with
// npm run dev and hitting them with postman this works fine
// rest of the code that doesn't get reached during the test...
}
@sabry-awad97
Copy link

import { EventEmitter } from 'stream';
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request: NextRequest) {
  try {
    let { title, purpose } = {};

    if (request instanceof EventEmitter) {
      // If it's an instance of EventEmitter, use request.body directly
      title = request.body.title;
      purpose = request.body.purpose;
    } else {
      // Otherwise, use request.json()
      ({ title, purpose } = await request.json());
    }

    // Rest of the code
  } catch (error) {
    console.error(error);
    // Handle errors as needed
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment