Skip to content
338 changes: 242 additions & 96 deletions e2e/recipe-api.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,17 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Pool } from 'pg';
import { expect, test, type BrowserContext, type Page } from '@playwright/test';
import {
expect,
test,
type Browser,
type BrowserContext,
type Page,
} from '@playwright/test';
import { createApp } from '../apps/api/src/app.js';
import { createAuthRepository } from '../apps/api/src/features/auth/authRepository.js';
import { createAuthService } from '../apps/api/src/features/auth/authService.js';
import { createRecipeRepository } from '../apps/api/src/features/recipes/recipeRepository.js';

if (existsSync('.env')) process.loadEnvFile('.env');
test.skip(
Expand Down Expand Up @@ -95,16 +102,60 @@ async function register(page: Page, email: string) {
).toBeVisible();
}

test('persists recipes, uploaded images and ratings through the real API', async ({
page,
context,
browser,
}) => {
test.setTimeout(90000);
/*
* Independent scenarios. Each creates its own users and recipes, so a
* failure points at one feature and does not hide the rest. Users are
* created through the auth service (registration through the UI is rate
* limited to 5 per minute per IP) and get a real session cookie; the
* end-to-end journey at the bottom still registers through the UI.
*/
async function signedIn(browser: Browser, name: string) {
const { user, sessionToken } = await createAuthService(
createAuthRepository(pool, pool, schema),
).register(name, `${randomUUID()}@example.com`, 'browser-test-password');
const context = await browser.newContext({
baseURL: 'http://127.0.0.1:4173/project2/',
});
await connect(context);
await register(page, 'owner@example.com');
await context.addCookies([
{
name: 't31_project2_session',
value: sessionToken,
domain: '127.0.0.1',
path: '/',
httpOnly: true,
sameSite: 'Lax',
},
]);
return { user, context, page: await context.newPage() };
}

/** Creates a public recipe directly in the database for a scenario. */
async function createRecipe(authorId: string, title: string) {
const recipe = await createRecipeRepository(pool, schema).create(
{
title,
description: 'Created for a browser test.',
imageUrl: null,
category: 'soup',
cuisine: null,
difficulty: 'easy',
visibility: 'public',
prepMinutes: 5,
cookMinutes: 10,
servings: 2,
ingredients: [{ name: 'Water', amount: 1, unit: 'l', note: null }],
instructions: ['Boil water.'],
tags: [],
},
authorId,
);
return `recipes/${recipe.id}`;
}

async function fillRecipeForm(page: Page, title: string) {
await page.goto('recipes/new');
await page.getByLabel(/Recipe title/).fill('Browser soup');
await page.getByLabel(/Recipe title/).fill(title);
await page.getByLabel(/Preparation time/).fill('5');
await page.getByLabel(/Cooking time/).fill('10');
await page.getByLabel(/Difficulty/).selectOption('medium');
Expand All @@ -114,127 +165,222 @@ test('persists recipes, uploaded images and ratings through the real API', async
await page.getByLabel('Ingredient 1 amount').fill('1');
await page.getByLabel('Ingredient 1 unit').selectOption('l');
await page.getByLabel('Step 1', { exact: true }).fill('Boil water.');
const image = await page.evaluate(() => {
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
const context = canvas.getContext('2d')!;
context.fillStyle = '#f9a825';
context.fillRect(0, 0, 300, 200);
return canvas.toDataURL('image/png').split(',')[1]!;
});
await page
.getByLabel('Upload a recipe image', { exact: true })
.setInputFiles({
name: 'soup.png',
mimeType: 'image/png',
buffer: Buffer.from(image, 'base64'),
}

test('publishes a recipe with an uploaded image that persists, then removes the image', async ({
browser,
}) => {
const owner = await signedIn(browser, 'Image Chef');
const { page } = owner;
try {
await fillRecipeForm(page, 'Browser soup');
const image = await page.evaluate(() => {
const canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
const context = canvas.getContext('2d')!;
context.fillStyle = '#f9a825';
context.fillRect(0, 0, 300, 200);
return canvas.toDataURL('image/png').split(',')[1]!;
});
await page.getByRole('button', { name: 'Use image' }).click();
await expect(page.getByRole('img', { name: 'Recipe preview' })).toBeVisible();
await page.getByRole('button', { name: 'Publish recipe' }).click();
await expect(
page.getByRole('heading', { name: 'Browser soup' }),
).toBeVisible();
const recipeUrl = page.url();
await page.reload();
await expect(
page.getByRole('heading', { name: 'Browser soup' }),
).toBeVisible();
await expect(
page.getByRole('img', { name: 'Browser soup', exact: true }),
).toBeVisible();
expect(
await page
.getByRole('img', { name: 'Browser soup', exact: true })
.evaluate((image: HTMLImageElement) => image.naturalWidth),
).toBeGreaterThan(0);
await page.getByRole('link', { name: 'Edit Recipe' }).click();
await page.getByLabel(/Recipe title/).fill('Edited browser soup');
await page.getByRole('button', { name: 'Save changes' }).click();
await expect(
page.getByRole('heading', { name: 'Edited browser soup' }),
).toBeVisible();
.getByLabel('Upload a recipe image', { exact: true })
.setInputFiles({
name: 'soup.png',
mimeType: 'image/png',
buffer: Buffer.from(image, 'base64'),
});
await page.getByRole('button', { name: 'Use image' }).click();
await expect(
page.getByRole('img', { name: 'Recipe preview' }),
).toBeVisible();
await page.getByRole('button', { name: 'Publish recipe' }).click();
await expect(
page.getByRole('heading', { name: 'Browser soup' }),
).toBeVisible();
await page.reload();
const shown = page.getByRole('img', { name: 'Browser soup', exact: true });
await expect(shown).toBeVisible();
expect(
await shown.evaluate((element: HTMLImageElement) => element.naturalWidth),
).toBeGreaterThan(0);

const readerContext = await browser.newContext({
baseURL: 'http://127.0.0.1:4173/project2/',
});
await page.getByRole('link', { name: 'Edit Recipe' }).click();
await page.getByRole('button', { name: 'Remove image' }).click();
await page.getByRole('button', { name: 'Save changes' }).click();
await expect(
page.getByRole('heading', { name: 'Browser soup' }),
).toBeVisible();
await expect(
page.getByRole('img', { name: 'Browser soup', exact: true }),
).toHaveCount(0);
} finally {
await owner.context.close();
}
});

test('edits a recipe and keeps the change after reload', async ({
browser,
}) => {
const owner = await signedIn(browser, 'Editing Chef');
try {
await connect(readerContext);
const reader = await readerContext.newPage();
await register(reader, 'reader@example.com');
await reader.goto(recipeUrl);
await reader.getByRole('button', { name: 'Increase servings' }).click();
await reader
const recipeUrl = await createRecipe(owner.user.id, 'Soup to edit');
await owner.page.goto(recipeUrl);
await owner.page.getByRole('link', { name: 'Edit Recipe' }).click();
await owner.page.getByLabel(/Recipe title/).fill('Edited browser soup');
await owner.page.getByRole('button', { name: 'Save changes' }).click();
// Wait for the save to finish before reloading.
await expect(
owner.page.getByRole('heading', { name: 'Edited browser soup' }),
).toBeVisible();
await owner.page.reload();
await expect(
owner.page.getByRole('heading', { name: 'Edited browser soup' }),
).toBeVisible();
} finally {
await owner.context.close();
}
});

test('another user rates a recipe, changes the rating and removes it', async ({
browser,
}) => {
const owner = await signedIn(browser, 'Rated Chef');
const reader = await signedIn(browser, 'Rating Reader');
try {
const recipeUrl = await createRecipe(owner.user.id, 'Soup to rate');
const page = reader.page;
await page.goto(recipeUrl);
await page
.getByRole('button', { name: 'Increase servings' })
.first()
.click();
await page
.getByRole('button', { name: 'Rate this recipe', exact: true })
.click();
await reader.getByRole('radio', { name: '5 stars' }).check();
await reader.getByRole('button', { name: 'Save rating' }).click();
await page.getByRole('radio', { name: '5 stars' }).check();
await page.getByRole('button', { name: 'Save rating' }).click();
await expect(
reader.getByText('Rating saved.', { exact: true }),
page.getByText('Rating saved.', { exact: true }),
).toBeVisible();
// Rating does not reset the chosen servings.
await expect(
reader
page
.getByRole('region', { name: 'Ingredients' })
.getByText('3 servings', { exact: true }),
).toBeVisible();
await page.reload();
await page.getByRole('button', { name: 'Your rating: 5/5' }).click();
await page.getByRole('radio', { name: '3 stars' }).check();
await page.getByRole('button', { name: 'Save rating' }).click();
await page.getByRole('button', { name: 'Your rating: 3/5' }).click();
await page.getByRole('button', { name: 'Remove rating' }).click();
await expect(
reader.getByRole('button', { name: 'Your rating: 5/5' }),
).toBeVisible();
await reader.reload();
await reader.getByRole('button', { name: 'Your rating: 5/5' }).click();
await reader.getByRole('radio', { name: '3 stars' }).check();
await reader.getByRole('button', { name: 'Save rating' }).click();
await reader.getByRole('button', { name: 'Your rating: 3/5' }).click();
await reader.getByRole('button', { name: 'Remove rating' }).click();
await expect(
reader.getByRole('button', { name: 'Rate Recipe' }),
page.getByRole('button', { name: 'Rate Recipe' }),
).toBeVisible();
await reader.getByRole('button', { name: 'Save to Cookbook' }).click();
} finally {
await owner.context.close();
await reader.context.close();
}
});

test('another user saves a recipe to My Cookbook and unsaves it there', async ({
browser,
}) => {
const owner = await signedIn(browser, 'Saved Chef');
const reader = await signedIn(browser, 'Saving Reader');
try {
const recipeUrl = await createRecipe(owner.user.id, 'Soup to save');
const page = reader.page;
await page.goto(recipeUrl);
await page.getByRole('button', { name: 'Save to Cookbook' }).click();
await expect(
reader.getByRole('button', { name: 'Saved', exact: true }),
page.getByRole('button', { name: 'Saved', exact: true }),
).toBeVisible();
await reader.goto('cookbook?view=saved');
await page.goto('cookbook?view=saved');
await expect(
reader.getByRole('link', { name: 'Edited browser soup' }),
page.getByRole('link', { name: 'Soup to save' }),
).toBeVisible();
await reader
.getByRole('button', {
name: 'Remove Edited browser soup from My Cookbook',
})
await page
.getByRole('button', { name: 'Remove Soup to save from My Cookbook' })
.click();
await reader.getByRole('button', { name: 'Unsave', exact: true }).click();
await page.getByRole('button', { name: 'Unsave', exact: true }).click();
await expect(
reader.getByRole('heading', { name: 'No saved recipes yet' }),
page.getByRole('heading', { name: 'No saved recipes yet' }),
).toBeVisible();
} finally {
await owner.context.close();
await reader.context.close();
}
});

await page.getByRole('link', { name: 'Edit Recipe' }).click();
await page.getByRole('button', { name: 'Remove image' }).click();
await page.getByLabel('Private', { exact: true }).check();
await page.getByRole('button', { name: 'Save changes' }).click();
test('a private recipe is hidden from other users, and a deleted recipe is gone', async ({
browser,
}) => {
const owner = await signedIn(browser, 'Private Chef');
const reader = await signedIn(browser, 'Curious Reader');
try {
const recipeUrl = await createRecipe(owner.user.id, 'Secret soup');
await owner.page.goto(recipeUrl);
await owner.page.getByRole('link', { name: 'Edit Recipe' }).click();
await owner.page.getByLabel('Private', { exact: true }).check();
await owner.page.getByRole('button', { name: 'Save changes' }).click();
await expect(
page.getByRole('heading', { name: 'Edited browser soup' }),
owner.page.getByRole('heading', { name: 'Secret soup' }),
).toBeVisible();
await reader.page.goto(recipeUrl);
await expect(
page.getByRole('img', { name: 'Edited browser soup', exact: true }),
).toHaveCount(0);
await reader.goto(recipeUrl);
await expect(
reader.getByRole('heading', { name: 'Recipe not found' }),
reader.page.getByRole('heading', { name: 'Recipe not found' }),
).toBeVisible();
await page
await owner.page
.getByRole('button', { name: 'Delete Recipe', exact: true })
.click();
await page
await owner.page
.getByRole('button', { name: 'Delete recipe', exact: true })
.click();
await expect(
page.getByRole('heading', { name: 'My Cookbook' }),
owner.page.getByRole('heading', { name: 'My Cookbook' }),
).toBeVisible();
await page.goto(recipeUrl);
await owner.page.goto(recipeUrl);
await expect(
owner.page.getByRole('heading', { name: 'Recipe not found' }),
).toBeVisible();
} finally {
await owner.context.close();
await reader.context.close();
}
});

test('end-to-end journey: register, publish, find it in Explore, and another user saves it', async ({
page,
context,
browser,
}) => {
test.setTimeout(60000);
const title = `Journey soup ${randomUUID().slice(0, 8)}`;
await connect(context);
await register(page, `${randomUUID()}@example.com`);
await fillRecipeForm(page, title);
await page.getByRole('button', { name: 'Publish recipe' }).click();
await expect(page.getByRole('heading', { name: title })).toBeVisible();

const readerContext = await browser.newContext({
baseURL: 'http://127.0.0.1:4173/project2/',
});
try {
await connect(readerContext);
const reader = await readerContext.newPage();
await register(reader, `${randomUUID()}@example.com`);
await reader.getByRole('searchbox').fill(title);
await reader.getByRole('searchbox').press('Enter');
await reader.getByRole('link', { name: title }).click();
await expect(reader.getByRole('heading', { name: title })).toBeVisible();
await reader.getByRole('button', { name: 'Save to Cookbook' }).click();
await expect(
page.getByRole('heading', { name: 'Recipe not found' }),
reader.getByRole('button', { name: 'Saved', exact: true }),
).toBeVisible();
await reader.goto('cookbook?view=saved');
await expect(reader.getByRole('link', { name: title })).toBeVisible();
} finally {
await readerContext.close();
}
Expand Down