T
TanStack3mo ago
rival-black

Unit testing routes and middleware

How do you test things like createServerFileRoute and createMiddleware? one example of what i'm trying to do (this code doesn't work):
import { csrfCheckMiddleware } from './csrf'; // this is a middleware i wrote with `createMiddleware`

it('throws a 401 Unauthorized error if no Authorization header is present', async () => {
vi.spyOn(serverUtils, 'getHeaders').mockReturnValue({});

const next = vi.fn();

await expect(
csrfCheckMiddleware({ next }) //this is not callable :(
).rejects.toThrow();

expect(next).not.toHaveBeenCalled();
});
import { csrfCheckMiddleware } from './csrf'; // this is a middleware i wrote with `createMiddleware`

it('throws a 401 Unauthorized error if no Authorization header is present', async () => {
vi.spyOn(serverUtils, 'getHeaders').mockReturnValue({});

const next = vi.fn();

await expect(
csrfCheckMiddleware({ next }) //this is not callable :(
).rejects.toThrow();

expect(next).not.toHaveBeenCalled();
});
i looked in the tanstack start codebase and it seems like these primitives only have type-level tests currently. does anyone have a working testing setup they can share?
3 Replies
sensitive-blue
sensitive-blue2w ago
I also want to know how to test middleware!!!
genetic-orange
genetic-orange2w ago
we will be adding test utilities for this after we reached stable status in start
sensitive-blue
sensitive-blue2w ago
👍

Did you find this page helpful?