test: cover echo message length boundaries

- Verify 500-character messages are accepted
- Verify messages exceeding 500 characters are rejected with HTTP 400
- Extract the Zod validation schema to module scope for reuse
This commit is contained in:
Brandon Wolfgang 2026-10-21 19:36:30 -05:00
parent 5546867449
commit c0ca16f166
2 changed files with 33 additions and 5 deletions

View file

@ -52,6 +52,19 @@ describe("API endpoints", () => {
}); });
}); });
it("POST /echo accepts a 500-character message", async () => {
const message = "a".repeat(500);
const response = await app.inject({
method: "POST",
url: "/echo",
payload: { message },
});
assert.equal(response.statusCode, 200);
assert.deepEqual(response.json(), { message });
});
it("POST /echo rejects an empty message", async () => { it("POST /echo rejects an empty message", async () => {
const response = await app.inject({ const response = await app.inject({
method: "POST", method: "POST",
@ -67,6 +80,21 @@ describe("API endpoints", () => {
}); });
}); });
it("POST /echo rejects a message longer than 500 characters", async () => {
const message = "a".repeat(501);
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",

View file

@ -1,6 +1,10 @@
import Fastify from "fastify"; import Fastify from "fastify";
import { z } from "zod"; import { z } from "zod";
const echoSchema = z.object({
message: z.string().min(1).max(500),
});
export const buildApp = () => { export const buildApp = () => {
const app = Fastify({ const app = Fastify({
logger: true, logger: true,
@ -18,11 +22,7 @@ export const buildApp = () => {
})); }));
app.post("/echo", async (request, reply) => { app.post("/echo", async (request, reply) => {
const schema = z.object({ const result = echoSchema.safeParse(request.body);
message: z.string().min(1).max(500),
});
const result = schema.safeParse(request.body);
if (!result.success) { if (!result.success) {
return reply.code(400).send({ return reply.code(400).send({