Next.js Discord

Discord Forum

Playwright with NextAuth jwt stategy

Unanswered
Oriental chestnut gall wasp posted this in #help-forum
Open in Discord
Original message was deleted.

2 Replies

Oriental chestnut gall wasp
My playwright fixture looks like this
tsimport { test as baseTest } from "@playwright/test";
import { PrismaClient } from "@prisma/client";
import fs from "fs";
import path from "path";
import { randomUUID } from "crypto";

const { encode } = await import("@auth/core/jwt");

export * from "@playwright/test";
export const test = baseTest.extend<{}, { workerStorageState: string }>({
  storageState: ({ workerStorageState }, use) => use(workerStorageState),

  workerStorageState: [
    async ({ browser }, use) => {
      const id = test.info().parallelIndex;
      const fileName = path.resolve(
        test.info().project.outputDir,
        `.auth/${id}.json`,
      );

      if (fs.existsSync(fileName)) {
        await use(fileName);
        return;
      }

      const page = await browser.newPage({ storageState: undefined });
      const prisma = new PrismaClient();

      const account = await prisma.user.upsert({
        where: {
          email: `testing${id}@example.com`,
        },
        create: {
          name: `Testing ${id}`,
          email: `testing${id}@example.com`,
        },
        update: {},
      });

      const token = encode({
        salt: `test-salt-${id}`,
        secret: process.env.AUTH_SECRET as string,
        maxAge: 1000 * 60 * 60,
        token: {
          name: `Testing ${id}`,
          email: `testing${id}@example.com`,
          picture: "https://placekitten.com/400/400",
          sub: account.id,
          jti: randomUUID(),
        },
      });

      await page.goto("http://localhost:3000/");
      await page.context().addCookies([
        {
          name: "authjs.session-token",
          value: await token,
          domain: "localhost",
          path: "/",
          httpOnly: true,
          sameSite: "Lax",
        },
      ]);

      await page.context().storageState({ path: fileName });
      await page.close();
      await use(fileName);
    },
    { scope: "worker" },
  ],
});
And I get following error, when starting the tests going on a auth page:

ReferenceError: crypto is not defined

    at encode (node_modules\@auth\core\jwt.js:54:17)