Comments (7)
Ah, yeah, the NextJS devs have the api-utils in four different locations across several versions 😅. This should be accounted for in the latest version of NTARH (v2.2.1). If you are able to update, does the problem go away?
from next-test-api-route-handler.
from next-test-api-route-handler.
Just to be sure: I meant only update NTARH, not NextJS. The latest NTARH should work with the older NextJS v11.0.x (integration tests are passing at least).
from next-test-api-route-handler.
So, updating to 2.2.1 gives me this error:
TypeError [ERR_INVALID_ARG_TYPE]: The "string" argument must be of type string or an instance of Buffer or ArrayBuffer. Received undefined
at ServerResponse.apiRes.end (node_modules/next/server/api-utils.ts:77:33)
at onerror (node_modules/next-connect/dist/index.cjs:4:47)
at node_modules/next-connect/dist/index.cjs:16:16
at apiResolver (node_modules/next/dist/server/api-utils.js:101:9)
from next-test-api-route-handler.
Interesting, this seems like the NextJS resolver function itself might have a problem with your handler, since NTARH doesn't call res.end
(only your handler and the resolver do).
First, does your handler code run in NextJS normally without errors?
Second, can you show me the code around your usage of the testApiHandler
function and the handler you're testing? Or better yet, if you can spin up a tiny dummy repo that reproduces your error, I can pinpoint the problem 🙂
from next-test-api-route-handler.
Of course! So, here's an example of how i use testApiHandler:
it("should fail if no parameters are passed", async () => {
await testApiHandler({
handler: storeMapHandler,
test: async ({ fetch }) => {
const res = await fetch({ method: "POST", headers, body: null });
expect(res.status).toBe(400);
expect(
((await res.json()) as FailedResponse).error.includes(
"Missing or Empty"
)
).toBe(true);
},
});
});
And here's the code for the handler itself:
import { VarBinary, MAX, PreparedStatement } from "mssql";
import nextConnect from "next-connect";
import { NextApiResponse } from "next";
import sessionMiddleware from "../middlewares/session";
import dbUtils from "../../../utils/db";
import { createBufferFromJSON } from "utils/helpers";
import { SessionedNextApiRequest } from "types/auth.types";
const handler = nextConnect();
handler.use(sessionMiddleware);
handler.post(
async (req: SessionedNextApiRequest, res: NextApiResponse, next) => {
if (req.headers["content-type"] !== "application/json") {
res.status(400).json({
error: Content-Type must be JSON
,
});
next(res);
}
const { id, mapProps } = req.body;
interface Body {
[key: string]: any;
}
const body: Body = {
user_id: req.user_id,
map_id: id,
map_properties: mapProps,
};
const requiredFields = ["user_id", "map_id", "map_properties"];
requiredFields.forEach((field) => {
if (!body.hasOwnProperty(field) || field === "" || !body[field]) {
res.status(400).json({ error: `Missing or Empty ${field}` });
next(res);
}
});
const { map_id, user_id, map_properties } = body;
try {
await dbUtils.connect();
await dbUtils.executePreparedStatementFunction(
async () =>
await executeStoreMap(map_id, Number(user_id), map_properties)
);
res.status(200).end();
next(res);
} catch (error) {
res.status(400).json({ error });
next(res);
}
next(res);
}
);
// There's no way for us to convert Strings to SQL Blobs ourselves, so have to use a PreparedStatement here.
const executeStoreMap = async (
map_id: string,
user_id: number,
map_properties: string
) => {
const mapProps = createBufferFromJSON(map_properties);
const statement = new PreparedStatement(dbUtils.db);
statement.input("mapProps", VarBinary(MAX));
await statement.prepare(INSERT INTO ${process.env.SHARED_MAPS_TABLE_NAME}(id, user_id, map_properties) VALUES('${map_id}', ${user_id}, @mapProps)
);
await statement.execute({ mapProps });
await statement.unprepare();
};
export default handler;
from next-test-api-route-handler.
Closing this in favor of #378. If this is a different issue and/or this wasn't solved by upgrading to [email protected]
, let me know and I'll reopen this.
from next-test-api-route-handler.
Related Issues (20)
- Relative URL doesn't work with appHandler: "Invalid URL" error HOT 4
- Insuffient type for `params` object given a well-typed dynamic route handler HOT 1
- Potential NTARH incompatibility with `next/jest.js` HOT 1
- originalGlobalFetch is not a function HOT 2
- Test file-uploading API Endpoint
- ValidationPipe not triggering in unit tests HOT 4
- next-test-api-route-handler (NTARH) failed to import api-utils.js HOT 2
- Verify support for app-based route handlers HOT 1
- Error: Invariant: Method expects to have requestAsyncStorage, none available HOT 3
- Incompatibility with [email protected] HOT 5
- Could not find a declaration file for module 'next-test-api-route-handler'. HOT 4
- Doesn't work in node 20.8.0 to 20.x HOT 7
- Bypassing MSW does not work with MSW 2.X HOT 2
- Vercel lambda governing compatibility badge isn't tracking latest compat version anymore HOT 1
- App Router Examples HOT 2
- Drop node-fetch in favor of native fetch functionality HOT 1
- Jest did not exit one second after the test run has completed. HOT 3
- Catch all segments dynamic api routes HOT 1
- Recursive redirection occurs when redirecting within the handler HOT 3
- ReferenceError: Request is not defined HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from next-test-api-route-handler.