Next.js Discord

Discord Forum

How to test cookies in route.ts?

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Given I have the following in my app code
//route.ts
export async function GET(request: Request) {
  const cookieStore = await cookies();
}

I can use
vi.mock("next/headers", () => {
  return {
    cookies: vi.fn(),
    headers: vi.fn(),
  };
});

to completely mock out cookies but I'd really like a functioning implementation of the cookie store like new CookieStore() or new RequestCookies(new Headers). Is there a way to construct the cookie store that nextjs uses internally? Or perhaps there's another implementation that would do the job?

1 Reply

Cape lionOP
In lieu of anything better this is a rough and ready implementation that seems to be sufficient for tests.

export const buildCookieStore = (
  cookieStore: Record<string, ResponseCookie> = {}
): ReadonlyRequestCookies => {
  const store = {
    get: (key: string) => cookieStore[key],
    set: (
      keyOrOptions: string | ResponseCookie,
      value?: string,
      cookieOptions?: Partial<ResponseCookie>
    ) => {
      if (typeof keyOrOptions === "string") {
        const key = keyOrOptions;
        cookieStore[key] = { name: key, value: value || "", ...cookieOptions };
      } else {
        const options = keyOrOptions;
        cookieStore[options.name] = options;
      }
      return store;
    },
    delete: (key: string) => {
      delete cookieStore[key];
      return store;
    },
    getAll: () => Object.values(cookieStore),
    has: (key: string) => key in cookieStore,
    size: Object.keys(cookieStore).length,
    [Symbol.iterator]: function* () {
      yield* Object.entries(cookieStore);
    },
  };