I am using Next.js to build a simple api and I make use of the automatic bodyParser Feature which parses the body based on the content-type (https://nextjs.org/docs/api-routes/api-middlewares). When fetching the api from the Frontend everything works
// index.jsx
export default function Home(props){
const handleClick = async () => {
await fetch(`/api/index.js`, {
body: JSON.stringify({
name: "My fancy name"
}),
method: "POST",
headers: {
"Content-Type": "application/json",
},
});
}
{
return(<button onClick={handleClick}>FETCH</button>)
}
// api/index.js
export default async function handler(req, res) {
switch (req.method) {
case "POST":
// Works since it gets parsed automatically
console.log(req.body.name)
res.status(200).json({message:"Okay"});
break;
default:
break;
}
}
My problems arise when writing tests for the api with jest and node-mocks-http. I can´t manage to create a request which gets parsed automatically.
import handler from "pages/api/index.js";
import { createMocks } from "node-mocks-http";
describe("POST", () => {
it("Returns Statuscode 200 on valid req", async () => {
const { req, res } = createMocks({
method: "POST",
body: JSON.stringify({
name: "Name of the object",
}),
headers: {
"Content-Type": "application/json",
},
});
await handler(req, res);
expect(res.statusCode).toBe(200);
});
});
Am I missing something important? I can´t really tell if my problem is based on next.js bodyParser or if it has to do with node-mocks-http. Any help leading me in the right direction is greatly appreciated!
Nevermind the solution to the problem is quite easy. Since the mocked request is no propper http request we do not need to stringify the body and act like it was automatically parsed.
import handler from "pages/api/index.js";
import { createMocks } from "node-mocks-http";
describe("POST", () => {
it("Returns Statuscode 200 on valid req", async () => {
const { req, res } = createMocks({
method: "POST",
body: {
name: "Name of the object",
},
headers: {
"Content-Type": "application/json",
},
});
await handler(req, res);
expect(res.statusCode).toBe(200);
});
});