test: add validation tests for POST /echo
- Test successful echo responses for valid messages - Verify empty messages are rejected with HTTP 400 - Validate request bodies using a Zod schema with a 1–500 character limit - Return a consistent error response for invalid request bodies
This commit is contained in:
parent
21d3da5d20
commit
5546867449
2 changed files with 49 additions and 0 deletions
|
|
@ -37,6 +37,36 @@ describe("API endpoints", () => {
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("POST /echo returns the validated message", async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/echo",
|
||||||
|
payload: {
|
||||||
|
message: "Hello, world!",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(response.statusCode, 200);
|
||||||
|
assert.deepEqual(response.json(), {
|
||||||
|
message: "Hello, world!",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("POST /echo rejects an empty message", async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: "POST",
|
||||||
|
url: "/echo",
|
||||||
|
payload: {
|
||||||
|
message: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(response.statusCode, 400);
|
||||||
|
assert.deepEqual(response.json(), {
|
||||||
|
error: "Invalid request body",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("returns 404 for an unknown endpoint", async () => {
|
it("returns 404 for an unknown endpoint", async () => {
|
||||||
const response = await app.inject({
|
const response = await app.inject({
|
||||||
method: "GET",
|
method: "GET",
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,5 @@
|
||||||
import Fastify from "fastify";
|
import Fastify from "fastify";
|
||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
export const buildApp = () => {
|
export const buildApp = () => {
|
||||||
const app = Fastify({
|
const app = Fastify({
|
||||||
|
|
@ -16,6 +17,24 @@ export const buildApp = () => {
|
||||||
},
|
},
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
app.post("/echo", async (request, reply) => {
|
||||||
|
const schema = z.object({
|
||||||
|
message: z.string().min(1).max(500),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = schema.safeParse(request.body);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
return reply.code(400).send({
|
||||||
|
error: "Invalid request body",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
message: result.data.message,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue