我使用Next.js构建了一个简单的api,并使用了基于内容类型(https://nextjs.org/docs/api-routes/api-middlewares)解析主体的自动bodyParser特性。当从前端获取api时,一切都正常。
// 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;
}
}
当使用node-mocks-http.和jest编写api测试时,我的问题出现了。我无法创建一个自动解析的请求。
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);
});
});
我错过了什么重要的事情吗?我真的无法判断我的问题是基于next.js bodyParser,还是与节点模拟-http有关。任何帮助引导我朝着正确的方向前进是非常感谢的!
发布于 2022-06-09 12:11:50
无论如何,解决这个问题是很容易的。由于模拟的请求不是propper请求,所以我们不需要对身体进行压缩,并表现为它被自动解析。
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);
});
});
https://stackoverflow.com/questions/72559755
复制相似问题