Skip to content
Draft
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions apps/example-todo-app/pages/api/todo/form-add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ import { z } from "zod"
import { v4 as uuidv4 } from "uuid"
import { HttpException } from "nextlove"

export const formData = z.object({
id: z.string().uuid().optional().default(uuidv4()),
title: z.string(),
completed: z.boolean().optional().default(false),
})
export const formData = z
.object({
id: z.string().uuid().optional().default(uuidv4()),
title: z.string(),
completed: z.boolean().optional().default(false),
})
.optional()

export const route_spec = checkRouteSpec({
methods: ["POST"],
Expand Down
35 changes: 34 additions & 1 deletion apps/example-todo-app/tests/api/todo/form-add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import test from "ava"
import { TODO_ID } from "tests/fixtures"
import getTestServer from "tests/fixtures/get-test-server"
import { v4 as uuidv4 } from "uuid"
import { formData } from "pages/api/todo/form-add"
import { z } from "zod"
import qs from "qs"

test("POST /todo/form-add", async (t) => {
const { axios } = await getTestServer(t)
Expand All @@ -23,3 +24,35 @@ test("POST /todo/form-add", async (t) => {

t.is(successfulRes.status, 200)
})

test("Valid formData object passes validation and returns successful response", async (t) => {
const { axios } = await getTestServer(t)

axios.defaults.headers.common.Authorization = `Bearer auth_token`

const validFormData = {
title: "test title",
clear_sandbox_state: "clear_sandbox_state",
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
clear_sandbox_state: "clear_sandbox_state",
completed: true,

}

const formDataString = qs.stringify(validFormData)

const successfulRes = await axios({
method: "POST",
url: "/todo/form-add",
data: formDataString,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}).catch((err) => err)

const formDataSchema = z
.object({
title: z.string(),
clear_sandbox_state: z.literal("clear_sandbox_state"),
})
.safeParse(validFormData)

t.true(formDataSchema.success)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const formDataSchema = z
.object({
title: z.string(),
clear_sandbox_state: z.literal("clear_sandbox_state"),
})
.safeParse(validFormData)
t.true(formDataSchema.success)

t.is(successfulRes.status, 200)
})
Loading