forwardemail / forwardemail/supertest

How can I test dynamic next.js API route using supertest in an integration test scenario?

Open
#769 9 comments 6 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
14.4k
Forks
782
PR merge metrics
No merged PRs in 30d

Description

I have this simple example of testing an API route using supertest. I want to do an "integration test". So I want to hit the actual API, execute all the code in the API handler and test the result.

It works fine until I try to read a query parameter in a [dynamic API route](https://nextjs.org/docs/api-routes/dynamic-api-routes).

Repo: https://github.com/riha/test-supertest

Next.js dynamic API `/api/[name].ts`

```
import type { NextApiRequest, NextApiResponse } from "next";

type Data = {
name: string;
};

export default function handler(
req: NextApiRequest,
res: NextApiResponse
) {
console.log(req);
// nothing get inserted into req.query 🥺
const name = req.query.name as string;
res.status(200).json({ name: name });
}
```

And the test `__tests__/api/name.ts`

```
const testClient = (handler: NextApiHandler) => {
const listener: RequestListener = (req, res) => {
return apiResolver(
req,
res,
undefined,
handler,
{
previewModeEncryptionKey: "",
previewModeId: "",
previewModeSigningKey: "",
},
false
);
};

return request(createServer(listener));
};

it("What's my name!?", async () => {
const client = testClient(handler);
const response = await client.get("/api/name").query({ name: "John" });

console.log(response.body);

expect(true);
});
```

Test API gets called but the query parameter isn't parsed into the request object. So `req.query` is always `undefined`. I'm sure this is obvious to some? I guess I can't call the handler this way and that I somehow miss some next.js magic middleware?

But how can I do it differently?
Could I start a server and a port listener and call it using that somehow? Could I somehow create the handler differently?
Is there a way where I could also add the data to the request param object, before sending it, I guess that could work as well?

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.