T
TanStack7mo ago
vicious-gold

How to test ServerFn with vitest ?

Hey guys, I am trying to add some tests with vitest into my tanstack start app. And I tought I would test the bunch of serverFns that I have. I am using vitest for my testing framework and testcontainer to mock my db. So far those 2 libraries are working fine. However when I try to call a serverFn in vitest I get the following error:
stderr | app/auth/auth.test.ts
[AsyncFunction (anonymous)]
Warning: createServerFn must be called with a function that has a 'url' property. Ensure that the @tanstack/start-plugin is ordered **before** the @tanstack/server-functions-plugin.
stderr | app/auth/auth.test.ts
[AsyncFunction (anonymous)]
Warning: createServerFn must be called with a function that has a 'url' property. Ensure that the @tanstack/start-plugin is ordered **before** the @tanstack/server-functions-plugin.
Here is what my test looks like: auth.test.ts
import { describe, expect, test } from "vitest";
import { dummyAction } from "./dummy.actions";

describe("todo", () => {
test("todo", async () => {
await dummyAction();

expect(10).toBe(10);
});
});
import { describe, expect, test } from "vitest";
import { dummyAction } from "./dummy.actions";

describe("todo", () => {
test("todo", async () => {
await dummyAction();

expect(10).toBe(10);
});
});
dummy.actions.ts
export const dummyAction = createServerFn({ method: "POST" })
.middleware([injectDbMiddleware])
.handler(async ({ context }) => {
console.log(context); // context does not contain the db

// await context.db.insert(userTable).values({
// email: "hello@google.com",
// name: "hello",
// });
});
export const dummyAction = createServerFn({ method: "POST" })
.middleware([injectDbMiddleware])
.handler(async ({ context }) => {
console.log(context); // context does not contain the db

// await context.db.insert(userTable).values({
// email: "hello@google.com",
// name: "hello",
// });
});
db.middlewares.ts
import { createMiddleware } from "@tanstack/start";
import { getDb } from "~/libs/db";

export const injectDbMiddleware = createMiddleware().server(({ next }) => {
const { db } = getDb();
console.log("HERE"); // this doesn't show up in the log

return next({
context: {
db,
},
});
});
import { createMiddleware } from "@tanstack/start";
import { getDb } from "~/libs/db";

export const injectDbMiddleware = createMiddleware().server(({ next }) => {
const { db } = getDb();
console.log("HERE"); // this doesn't show up in the log

return next({
context: {
db,
},
});
});
2 Replies
deep-jade
deep-jade7mo ago
Also interested in this!
vicious-gold
vicious-goldOP6mo ago
out of interest is this plan / technically achievable ? Or should I go about using a different testing strategy ? How do you guys test your tanstack app ?

Did you find this page helpful?