TanStackT
TanStack11mo ago
2 replies
forward-apricot

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.


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);
  });
});


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",
    // });
  });


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,
    },
  });
});
Was this page helpful?