T
TanStack7mo ago
continuing-cyan

Testing Server Functions with vitest (including validation + middleware)

Hi friends - looking to write tests for my server functions (preferring vitest, but openminded). With my current implementation, the "result" of my function call is undefined even when logs inside the function body show that it should be returning data. Additionally, it looks like middleware and validator functions are not running (I'm seeing no logs from my middleware functions, and not getting the expected errors from validation or auth middleware). Looking for any guidance on the write setup here! Example code: createUser.ts
const createUserSchema = z
.object({
name: z.string(),
email: z.string().email(),
role: z.enum(user_roles),
})
.strict()

export const createUser = createServerFn({ method: "POST" })
.middleware([adminAuthorizationMiddleware])
.validator(createUserSchema)
.handler(async ({ data }) => {
const result = await db
.insert(user_table)
.values({
name: data.name,
email: data.email,
email_verified: false,
role: data.role,
})
.returning()
.then(res => res[0])

console.log("Created user", result)
return result
})
const createUserSchema = z
.object({
name: z.string(),
email: z.string().email(),
role: z.enum(user_roles),
})
.strict()

export const createUser = createServerFn({ method: "POST" })
.middleware([adminAuthorizationMiddleware])
.validator(createUserSchema)
.handler(async ({ data }) => {
const result = await db
.insert(user_table)
.values({
name: data.name,
email: data.email,
email_verified: false,
role: data.role,
})
.returning()
.then(res => res[0])

console.log("Created user", result)
return result
})
createUser.test.ts
test("validates email format", async () => {
const name = "_TEST_" + faker.person.fullName()
const invalidData = {
name: name,
email: name,
role: "driver" as const,
}

// ERROR BELOW IS ALWAYS UNDEFINED
const error = await createUser({
data: invalidData,
}).catch(e => e)

// Check for specific validation error
expect(error.message).toContain("Invalid email")
})
test("validates email format", async () => {
const name = "_TEST_" + faker.person.fullName()
const invalidData = {
name: name,
email: name,
role: "driver" as const,
}

// ERROR BELOW IS ALWAYS UNDEFINED
const error = await createUser({
data: invalidData,
}).catch(e => e)

// Check for specific validation error
expect(error.message).toContain("Invalid email")
})
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?