63 lines
1.6 KiB
TypeScript
63 lines
1.6 KiB
TypeScript
|
|
import fs from 'node:fs';
|
||
|
|
import path from 'node:path';
|
||
|
|
import {
|
||
|
|
type APIRequestContext,
|
||
|
|
type Browser,
|
||
|
|
type BrowserContext,
|
||
|
|
expect,
|
||
|
|
type Page,
|
||
|
|
} from '@playwright/test';
|
||
|
|
import { generateId } from 'ai';
|
||
|
|
import { getUnixTime } from 'date-fns';
|
||
|
|
|
||
|
|
export type UserContext = {
|
||
|
|
context: BrowserContext;
|
||
|
|
page: Page;
|
||
|
|
request: APIRequestContext;
|
||
|
|
};
|
||
|
|
|
||
|
|
export async function createAuthenticatedContext({
|
||
|
|
browser,
|
||
|
|
name,
|
||
|
|
}: {
|
||
|
|
browser: Browser;
|
||
|
|
name: string;
|
||
|
|
}): Promise<UserContext> {
|
||
|
|
const authDir = path.join(__dirname, '../playwright/.auth');
|
||
|
|
|
||
|
|
if (!fs.existsSync(authDir)) {
|
||
|
|
fs.mkdirSync(authDir, { recursive: true });
|
||
|
|
}
|
||
|
|
|
||
|
|
const storageFile = path.join(authDir, `${name}.json`);
|
||
|
|
|
||
|
|
const context = await browser.newContext();
|
||
|
|
const page = await context.newPage();
|
||
|
|
|
||
|
|
const email = `test-${name}-${getUnixTime(new Date())}@playwright.com`;
|
||
|
|
const password = generateId(16);
|
||
|
|
|
||
|
|
await page.goto('http://localhost:3000/register');
|
||
|
|
await page.getByPlaceholder('user@acme.com').click();
|
||
|
|
await page.getByPlaceholder('user@acme.com').fill(email);
|
||
|
|
await page.getByLabel('Password').click();
|
||
|
|
await page.getByLabel('Password').fill(password);
|
||
|
|
await page.getByRole('button', { name: 'Sign Up' }).click();
|
||
|
|
|
||
|
|
await expect(page.getByTestId('toast')).toContainText(
|
||
|
|
'Account created successfully!',
|
||
|
|
);
|
||
|
|
|
||
|
|
await context.storageState({ path: storageFile });
|
||
|
|
await page.close();
|
||
|
|
|
||
|
|
const newContext = await browser.newContext({ storageState: storageFile });
|
||
|
|
const newPage = await newContext.newPage();
|
||
|
|
|
||
|
|
return {
|
||
|
|
context: newContext,
|
||
|
|
page: newPage,
|
||
|
|
request: newContext.request,
|
||
|
|
};
|
||
|
|
}
|