test: replace ad-hoc tests with a layered suite and CI workflow

Splits testing into five layers so a failure points at the responsible one:

- tests/unit    isolated utility, repository and service tests
- tests/data    validates the tracked Pokémon, game, region and dex files
- tests/integration  schema, views, constraints, RLS and repositories
- tests/bdd     executable Gherkin for user-visible behaviour
- tests/build   service worker and manifest artifacts per build variant

Replaces the two Playwright specs in client-test/ and the two Vitest files in
test/. Adds a GitHub Actions workflow running the layers as separate jobs, a
mock OAuth provider server so the Drive and Dropbox scenarios never touch real
accounts, and a wrapper that reads the local Supabase keys from
`supabase status` rather than hard-coding them.

Extracts the pure formatting helpers out of PokedexExportService so they can be
unit tested, and makes the provider endpoints configurable so the mock server
can stand in for Google and Dropbox.
This commit is contained in:
Josh Creek
2026-09-13 17:35:04 +01:00
parent 08c5e3271c
commit de39dc78ea
52 changed files with 3390 additions and 397 deletions
+47
View File
@@ -0,0 +1,47 @@
Feature: Account access
As a trainer
I want secure access to my account
So that only I can update my collection
Scenario: Register a new account
Given I am a new visitor
When I register with valid account details
Then I am told to confirm my email
And a confirmation email is captured locally
Scenario: Sign in with valid credentials
Given I have a confirmed account
When I sign in with my credentials
Then I arrive at my Pokédex list
Scenario: Reject invalid credentials
Given I have a confirmed account
When I sign in with an incorrect password
Then I see a sign-in error
Scenario: Redirect an authenticated visitor
Given I am signed in
When I visit the public home page
Then I arrive at my Pokédex list
Scenario: Sign out
Given I am signed in
When I sign out
Then I return to the public home page
Scenario: Request a password reset
Given I have a confirmed account
When I request a password reset
Then a password reset email is captured locally
@product-review
Scenario: Reject mismatched replacement passwords
Given I am on the password reset page with a recovery session
When I enter two different replacement passwords
Then I am told that the passwords do not match
Scenario: Complete a password reset
Given I am on the password reset page with a recovery session
When I enter a valid replacement password
Then I am told that my password was updated
+43
View File
@@ -0,0 +1,43 @@
Feature: Backup and export
As a trainer
I want changes exported to my connected storage
So that I retain a portable backup
Background:
Given I am signed in
Scenario: Show disconnected backup providers
When I visit backup settings
Then Google Drive and Dropbox are shown as not connected
Scenario Outline: Connect a backup provider
When I connect the mocked "<provider>" provider
Then "<provider>" is shown as connected
Examples:
| provider |
| Google Drive |
| Dropbox |
Scenario: Reject an invalid OAuth state
When a mocked OAuth callback has an invalid state
Then the backup connection is rejected
Scenario: Export escaped catch data without losing the update
Given Google Drive is connected to the mocked provider
And I have a Living Dex named "Quoted, Dex"
When I save a catch note containing a comma and quote
Then the mocked provider receives a valid escaped CSV
And the catch update remains saved
Scenario: Refresh an expired provider token
Given Dropbox is connected with an expired token
When an export is requested
Then the token is refreshed before the mocked upload
Scenario: Record provider failure without losing progress
Given Google Drive is connected to a failing mocked provider
When I update collection progress
Then the catch update remains saved
And the provider failure is shown in backup settings
@@ -0,0 +1,32 @@
Feature: Pokédex composition
As a trainer
I want the correct Pokémon in each configured dex
So that completion totals are trustworthy
Background:
Given I am signed in
Scenario: Build a national Living Dex from canonical forms
Given I have a Living Dex named "National"
When I inspect its entries without forms
Then it contains 1025 unique species
And named default forms are represented once
Scenario: Include all supported forms
Given I have a Form Dex named "Forms"
When I inspect its entries with forms
Then every entry identity is unique
And Basculin has 3 forms
And Alcremie has 63 forms
And Unown has 28 forms
Scenario: Render shiny artwork
Given I have a Shiny Dex named "Shinies"
When I view the Pokédex
Then its Pokémon use shiny sprites
Scenario: Respect game and dex scope
Given I have a Form Dex named "Black Forms" scoped to game "Black" and dex "Unova"
When I inspect its entries with forms
Then Rotom includes its named default form without duplicate forms
@@ -0,0 +1,57 @@
Feature: Pokédex lifecycle
As a trainer
I want to configure and manage Pokédexes
So that each collection matches my goal
Background:
Given I am signed in
Scenario: See the empty state
Given I have no Pokédexes
When I visit my Pokédex list
Then I see the empty Pokédex message
Scenario: Validate a new Pokédex
When I open the new Pokédex form
Then I cannot create a Pokédex without a name and type
Scenario Outline: Create each supported Pokédex type
When I create a Pokédex named "<name>" of type "<type>"
Then the Pokédex "<name>" is available to view
Examples:
| name | type |
| Living | Living Dex |
| Shiny | Shiny Dex |
| Origin | Origin Dex |
| Every Form | Form Dex |
Scenario: Create a game and dex scoped Pokédex
When I create a Living Dex named "Black Regional" scoped to game "Black" and dex "Unova"
Then the Pokédex "Black Regional" is available to view
Scenario: Reject a duplicate name
Given I have a Living Dex named "My Collection"
When I try to create another Living Dex named "My Collection"
Then I am told that the Pokédex name is already used
Scenario: Edit a Pokédex
Given I have a Living Dex named "Before Editing"
When I rename it to "After Editing" and enable forms
Then the Pokédex "After Editing" is available to view
Scenario: Cancel deleting a Pokédex
Given I have a Living Dex named "Keep Me"
When I cancel deleting "Keep Me"
Then the Pokédex "Keep Me" is available to view
Scenario: Delete a Pokédex
Given I have a Living Dex named "Delete Me"
When I confirm deleting "Delete Me"
Then the Pokédex "Delete Me" is no longer listed
Scenario: Keep another user's Pokédex private
Given another trainer has a Pokédex
When I request the other trainer's Pokédex
Then the Pokédex is not disclosed
@@ -0,0 +1,38 @@
Feature: Progress tracking
As a trainer
I want to record collection state
So that my Pokédex shows what remains
Background:
Given I am signed in
And I have a Living Dex named "Progress"
And I view the Pokédex
Scenario: Mark a Pokémon caught
When I mark the first Pokémon as caught
Then the first Pokémon is shown as caught after reloading
Scenario: Keep caught and needs-to-evolve mutually exclusive
When I mark the first Pokémon as caught
And I mark the first Pokémon as needing evolution
Then the first Pokémon needs evolution and is not marked caught
Scenario: Record HOME state and notes
When I mark the first Pokémon as in HOME
And I add the note "Caught, traded, and checked" to the first Pokémon
Then its HOME state and note persist after reloading
Scenario: Update an entire box
When I mark box 1 as caught
Then box 1 contains 30 caught Pokémon
Scenario: Filter collection progress
When I mark the first Pokémon as caught
And I filter to Pokémon that are not caught
Then the caught Pokémon is filtered out
Scenario: Remember box layout density
When I select the "Compact" box layout
And I reload the Pokédex
Then the "Compact" box layout remains selected
+19
View File
@@ -0,0 +1,19 @@
Feature: Offline-friendly application
As a trainer
I want the installed site to survive network loss
So that I can consult my collection anywhere
Scenario: Register the service worker
When I open the built application
Then a service worker controls the page
And the application cache is present
Scenario: Navigate while offline
Given I have opened the built application online
When I go offline and revisit the home page with a trailing slash
Then the application remains available
Scenario: Restore network access
Given I have opened the built application online
When I go offline and then return online
Then the application remains available
+39
View File
@@ -0,0 +1,39 @@
import { test as base } from 'playwright-bdd';
export type ScenarioState = {
email: string;
password: string;
replacementPassword: string;
userId: string | null;
pokedexId: string | null;
pokedexName: string | null;
entries: Array<{ pokemon: string; form: string | null; num: number; id: string }>;
lastResponseStatus: number | null;
lastMessage: string | null;
};
type Fixtures = { state: ScenarioState };
export const test = base.extend<Fixtures>({
// Playwright fixture callbacks require the dependency object even when this fixture has none.
// eslint-disable-next-line no-empty-pattern
state: async ({}, use, testInfo) => {
const slug = testInfo.testId
.replace(/[^a-z0-9]/gi, '')
.slice(-18)
.toLowerCase();
await use({
email: `bdd-${slug}-${Date.now()}@example.test`,
password: 'BddPassword123!',
replacementPassword: 'BddReplacement456!',
userId: null,
pokedexId: null,
pokedexName: null,
entries: [],
lastResponseStatus: null,
lastMessage: null
});
}
});
export { expect } from '@playwright/test';
+111
View File
@@ -0,0 +1,111 @@
import { createBdd } from 'playwright-bdd';
import { test, expect } from '../fixtures';
import { createConfirmedUser, signIn } from '../support/app';
const { Given, When, Then } = createBdd(test);
const MAILPIT_URL = process.env.TEST_MAILPIT_URL ?? 'http://127.0.0.1:54324';
async function mailCountFor(email: string, subject: string): Promise<number> {
const response = await fetch(
`${MAILPIT_URL}/api/v1/search?query=${encodeURIComponent(`to:${email} subject:${subject}`)}`
);
if (!response.ok) throw new Error(`MailPit is unavailable: ${response.status}`);
const body = (await response.json()) as { total?: number; messages?: unknown[] };
return body.total ?? body.messages?.length ?? 0;
}
Given('I am a new visitor', async ({ page }) => {
await page.goto('/');
});
Given('I have a confirmed account', async ({ state }) => {
await createConfirmedUser(state);
});
Given('I am signed in', async ({ page, state }) => {
await createConfirmedUser(state);
await signIn(page, state);
await expect(page).toHaveURL(/\/my-pokedexes$/);
});
Given('I am on the password reset page with a recovery session', async ({ page, state }) => {
await createConfirmedUser(state);
await signIn(page, state);
await expect(page).toHaveURL(/\/my-pokedexes$/);
await page.goto('/reset-password');
});
When('I register with valid account details', async ({ page, state }) => {
await page.getByLabel('Email').fill(state.email);
await page.getByLabel('Password').fill(state.password);
await page.getByRole('button', { name: 'Sign Up', exact: true }).first().click();
});
When('I sign in with my credentials', async ({ page, state }) => {
await signIn(page, state);
});
When('I sign in with an incorrect password', async ({ page, state }) => {
await signIn(page, state, `${state.password}-incorrect`);
});
When('I visit the public home page', async ({ page }) => {
await page.goto('/');
});
When('I sign out', async ({ page }) => {
await page.getByRole('button', { name: 'usericon' }).click();
await page.getByRole('button', { name: 'Sign Out', exact: true }).click();
});
When('I request a password reset', async ({ page, state }) => {
await page.goto('/forgot-password');
await page.getByLabel('Email').fill(state.email);
await page.getByRole('button', { name: 'Send Reset Link' }).click();
});
When('I enter two different replacement passwords', async ({ page, state }) => {
await page.getByLabel('New Password').fill(state.replacementPassword);
await page.getByLabel('Confirm Password').fill(`${state.replacementPassword}-different`);
await page.getByRole('button', { name: 'Update Password' }).click();
});
When('I enter a valid replacement password', async ({ page, state }) => {
await page.getByLabel('New Password').fill(state.replacementPassword);
await page.getByLabel('Confirm Password').fill(state.replacementPassword);
await page.getByRole('button', { name: 'Update Password' }).click();
});
Then('I am told to confirm my email', async ({ page }) => {
await expect(page).toHaveURL(/\/welcome$/);
await expect(page.getByText('Check Your Email', { exact: true })).toBeVisible();
});
Then('a confirmation email is captured locally', async ({ state }) => {
await expect.poll(() => mailCountFor(state.email, 'Confirm')).toBeGreaterThan(0);
});
Then('I arrive at my Pokédex list', async ({ page }) => {
await expect(page).toHaveURL(/\/my-pokedexes$/);
});
Then('I see a sign-in error', async ({ page }) => {
await expect(page.locator('.alert-error')).toBeVisible();
});
Then('I return to the public home page', async ({ page }) => {
await expect(page).toHaveURL(/\/$/);
});
Then('a password reset email is captured locally', async ({ page, state }) => {
await expect(page.getByText('Check your email for the password reset link')).toBeVisible();
await expect.poll(() => mailCountFor(state.email, 'Reset')).toBeGreaterThan(0);
});
Then('I am told that the passwords do not match', async ({ page }) => {
await expect(page.getByText('Passwords do not match')).toBeVisible();
});
Then('I am told that my password was updated', async ({ page }) => {
await expect(page.getByText(/Password updated successfully/)).toBeVisible();
});
+156
View File
@@ -0,0 +1,156 @@
import { createBdd } from 'playwright-bdd';
import { test, expect } from '../fixtures';
import { createDexThroughUi, firstPokemon, openFirstPokemon } from '../support/app';
const { Given, When, Then } = createBdd(test);
const MOCK_URL = process.env.MOCK_PROVIDER_URL ?? 'http://127.0.0.1:4199';
const SUPABASE_URL = process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321';
type Provider = 'google_drive' | 'dropbox';
async function seedIntegration(
state: import('../fixtures').ScenarioState,
provider: Provider,
overrides: Record<string, unknown> = {}
) {
const key = process.env.E2E_SERVICE_ROLE_KEY;
if (!key || !state.userId)
throw new Error('A confirmed user and E2E_SERVICE_ROLE_KEY are required');
const response = await fetch(`${SUPABASE_URL}/rest/v1/pokedex_export_integrations`, {
method: 'POST',
headers: {
apikey: key,
Authorization: `Bearer ${key}`,
'Content-Type': 'application/json',
Prefer: 'resolution=merge-duplicates,return=representation'
},
body: JSON.stringify({
userId: state.userId,
pokedexId: null,
provider,
enabled: true,
accessToken: 'mock-access-token',
refreshToken: 'mock-refresh-token',
accessTokenExpiresAt: new Date(Date.now() + 3_600_000).toISOString(),
...overrides
})
});
if (!response.ok) throw new Error(await response.text());
}
async function ensureExportDex(
page: import('@playwright/test').Page,
state: import('../fixtures').ScenarioState
) {
if (!state.pokedexId) {
await createDexThroughUi(page, state, {
name: state.pokedexName ?? `Export ${Date.now()}`,
type: 'Living Dex'
});
}
}
Given('Google Drive is connected to the mocked provider', async ({ state }) => {
await seedIntegration(state, 'google_drive');
});
Given('Dropbox is connected with an expired token', async ({ page, state }) => {
await seedIntegration(state, 'dropbox', {
accessTokenExpiresAt: new Date(Date.now() - 60_000).toISOString()
});
await ensureExportDex(page, state);
});
Given('Google Drive is connected to a failing mocked provider', async ({ page, state }) => {
await seedIntegration(state, 'google_drive');
await fetch(`${MOCK_URL}/__mock/fail-uploads`);
await ensureExportDex(page, state);
});
When('I visit backup settings', async ({ page }) => {
await page.goto('/backup-settings');
});
When('I connect the mocked {string} provider', async ({ page }, provider: string) => {
await fetch(`${MOCK_URL}/__mock/reset`);
await page.goto('/backup-settings');
const card = page.locator('.card, .border').filter({ hasText: provider }).last();
await card.getByRole('button', { name: 'Connect' }).click();
await page.waitForURL(/\/backup-settings\?export=.*-connected/);
});
When('a mocked OAuth callback has an invalid state', async ({ page, state }) => {
const response = await page.request.get(
'/api/integrations/google-drive/callback?code=mock&state=invalid-state'
);
state.lastResponseStatus = response.status();
});
When('I save a catch note containing a comma and quote', async ({ page, state }) => {
await ensureExportDex(page, state);
await page.goto(`/pokedex/${state.pokedexId}`);
await openFirstPokemon(page);
await page.getByRole('dialog').getByLabel('Notes:').fill('A comma, and a "quote"');
await page.getByRole('dialog').getByLabel('Notes:').blur();
await expect(page.getByText(/Saving…/)).toHaveCount(0, { timeout: 15_000 });
});
When('an export is requested', async ({ page, state }) => {
const response = await page.request.post(`/api/pokedexes/${state.pokedexId}/export`);
state.lastResponseStatus = response.status();
});
When('I update collection progress', async ({ page, state }) => {
await page.goto(`/pokedex/${state.pokedexId}`);
await openFirstPokemon(page);
await page
.getByRole('dialog')
.getByText('Caught:', { exact: true })
.locator('..')
.getByRole('checkbox')
.check();
await expect(page.getByText(/Saving…/)).toHaveCount(0, { timeout: 15_000 });
});
Then('Google Drive and Dropbox are shown as not connected', async ({ page }) => {
await expect(page.getByText('Not Connected', { exact: true })).toHaveCount(2);
});
Then('{string} is shown as connected', async ({ page }, provider: string) => {
const card = page.locator('.border').filter({ hasText: provider });
await expect(card.getByText('Connected', { exact: true })).toBeVisible();
});
Then('the backup connection is rejected', async ({ state }) => {
expect(state.lastResponseStatus).toBe(400);
});
Then('the mocked provider receives a valid escaped CSV', async () => {
const response = await fetch(`${MOCK_URL}/__mock/state`);
const mock = (await response.json()) as { requests: Array<{ path: string; body: string }> };
const upload = mock.requests.find((request) => request.path.includes('upload'));
expect(upload?.body).toContain('"A comma, and a ""quote"""');
});
Then('the catch update remains saved', async ({ page, state }) => {
await page.goto(`/pokedex/${state.pokedexId}`);
await expect(firstPokemon(page)).toBeVisible();
await openFirstPokemon(page);
const dialog = page.getByRole('dialog');
const caught = dialog.getByText('Caught:', { exact: true }).locator('..').getByRole('checkbox');
const notes = dialog.getByLabel('Notes:');
expect((await caught.isChecked()) || (await notes.inputValue()).includes('comma')).toBe(true);
});
Then('the token is refreshed before the mocked upload', async ({ state }) => {
expect(state.lastResponseStatus).toBe(200);
const response = await fetch(`${MOCK_URL}/__mock/state`);
const mock = (await response.json()) as { refreshes: number; requests: Array<{ path: string }> };
expect(mock.refreshes).toBeGreaterThan(0);
expect(mock.requests.some((request) => request.path.includes('upload'))).toBe(true);
});
Then('the provider failure is shown in backup settings', async ({ page }) => {
await page.goto('/backup-settings');
await expect(page.getByText(/mock upload failure/)).toBeVisible();
});
+65
View File
@@ -0,0 +1,65 @@
import { createBdd } from 'playwright-bdd';
import { test, expect } from '../fixtures';
import { loadEntries } from '../support/app';
const { When, Then } = createBdd(test);
When('I inspect its entries without forms', async ({ page, state }) => {
await loadEntries(page, state, false);
});
When('I inspect its entries with forms', async ({ page, state }) => {
await loadEntries(page, state, true);
});
When('I view the Pokédex', async ({ page, state }) => {
if (!state.pokedexId) throw new Error('A Pokédex must exist before it can be viewed');
await page.goto(`/pokedex/${state.pokedexId}`);
await expect(page.getByRole('button', { name: /^View details for / }).first()).toBeVisible();
});
Then('it contains {int} unique species', async ({ state }, count: number) => {
expect(state.entries).toHaveLength(count);
expect(new Set(state.entries.map((entry) => entry.pokemon)).size).toBe(count);
});
Then('named default forms are represented once', async ({ state }) => {
for (const [pokemon, form] of Object.entries({
Basculin: 'Red-striped',
Tornadus: 'Incarnate Form',
Oricorio: 'Baile (Red)',
Zygarde: '50%',
Gimmighoul: 'Box Form',
Rotom: 'Lightbulb',
Unown: 'A'
})) {
expect(state.entries.filter((entry) => entry.pokemon === pokemon)).toEqual([
expect.objectContaining({ form })
]);
}
});
Then('every entry identity is unique', async ({ state }) => {
const identities = state.entries.map((entry) => `${entry.pokemon}|${entry.form ?? ''}`);
expect(new Set(identities).size).toBe(identities.length);
});
Then('{word} has {int} forms', async ({ state }, pokemon: string, count: number) => {
expect(state.entries.filter((entry) => entry.pokemon === pokemon)).toHaveLength(count);
});
Then('its Pokémon use shiny sprites', async ({ page }) => {
const first = page.locator('img[src*="/shiny/"]').first();
for (let attempts = 0; attempts < 10 && (await first.count()) === 0; attempts++) {
await page.mouse.wheel(0, 2500);
}
await expect(first).toBeVisible();
});
Then('Rotom includes its named default form without duplicate forms', async ({ state }) => {
const forms = state.entries
.filter((entry) => entry.pokemon === 'Rotom')
.map((entry) => entry.form ?? '');
expect(forms).toContain('Lightbulb');
expect(new Set(forms).size).toBe(forms.length);
});
+167
View File
@@ -0,0 +1,167 @@
import { createBdd } from 'playwright-bdd';
import { test, expect } from '../fixtures';
import { createDexThroughUi } from '../support/app';
const { Given, When, Then } = createBdd(test);
async function dexCard(page: Parameters<typeof createDexThroughUi>[0], name: string) {
await page.goto('/my-pokedexes');
const card = page.locator('.card').filter({ hasText: name }).first();
await expect(card).toBeVisible();
return card;
}
Given('I have no Pokédexes', async ({ page }) => {
await page.goto('/my-pokedexes');
await expect(
page.locator('.card').filter({ has: page.getByRole('button', { name: 'View' }) })
).toHaveCount(0);
});
Given('I have a Living Dex named {string}', async ({ page, state }, name: string) => {
await createDexThroughUi(page, state, { name, type: 'Living Dex' });
});
Given('I have a Form Dex named {string}', async ({ page, state }, name: string) => {
await createDexThroughUi(page, state, { name, type: 'Form Dex' });
});
Given(
'I have a Form Dex named {string} scoped to game {string} and dex {string}',
async ({ page, state }, name: string, game: string, dex: string) => {
await createDexThroughUi(page, state, { name, type: 'Form Dex', game, dex });
}
);
Given('I have a Shiny Dex named {string}', async ({ page, state }, name: string) => {
await createDexThroughUi(page, state, { name, type: 'Shiny Dex' });
});
Given('another trainer has a Pokédex', async ({ state }) => {
const url = process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321';
const key = process.env.E2E_SERVICE_ROLE_KEY;
if (!key) throw new Error('E2E_SERVICE_ROLE_KEY is required');
const headers = {
apikey: key,
Authorization: `Bearer ${key}`,
'Content-Type': 'application/json'
};
const userResponse = await fetch(`${url}/auth/v1/admin/users`, {
method: 'POST',
headers,
body: JSON.stringify({
email: `other-${Date.now()}@example.test`,
password: 'OtherPassword123!',
email_confirm: true
})
});
const other = (await userResponse.json()) as { id: string };
const dexResponse = await fetch(`${url}/rest/v1/pokedexes`, {
method: 'POST',
headers: { ...headers, Prefer: 'return=representation' },
body: JSON.stringify({ userId: other.id, name: 'Private', isLivingDex: true })
});
if (!dexResponse.ok) throw new Error(await dexResponse.text());
const [dex] = (await dexResponse.json()) as Array<{ id: string }>;
state.pokedexId = dex.id;
});
When('I visit my Pokédex list', async ({ page }) => {
await page.goto('/my-pokedexes');
});
When('I open the new Pokédex form', async ({ page }) => {
await page.goto('/my-pokedexes');
await page
.getByRole('button', { name: /Create (New|Your First) Pokédex/ })
.first()
.click();
});
When('I create a Pokédex named {string} of type {string}', async ({ page, state }, name, type) => {
await createDexThroughUi(page, state, { name, type });
});
When(
'I create a Living Dex named {string} scoped to game {string} and dex {string}',
async ({ page, state }, name: string, game: string, dex: string) => {
await createDexThroughUi(page, state, { name, type: 'Living Dex', game, dex });
}
);
When('I try to create another Living Dex named {string}', async ({ page, state }, name: string) => {
await page.goto('/my-pokedexes');
await page.getByRole('button', { name: 'Create New Pokédex', exact: true }).click();
const modal = page.locator('.modal-open');
await modal.getByLabel('Name').fill(name);
await modal.getByText('Living Dex', { exact: false }).locator('..').getByRole('checkbox').check();
page.once('dialog', async (dialog) => {
state.lastMessage = dialog.message();
await dialog.accept();
});
await modal.getByRole('button', { name: 'Create', exact: true }).click();
await expect.poll(() => state.lastMessage).not.toBeNull();
});
When('I rename it to {string} and enable forms', async ({ page }, name: string) => {
const card = await dexCard(page, 'Before Editing');
await card.getByRole('button', { name: 'Edit' }).click();
const modal = page.locator('.modal-open');
await modal.getByLabel('Name').fill(name);
await modal.getByText('Form Dex', { exact: false }).locator('..').getByRole('checkbox').check();
const response = page.waitForResponse(
(candidate) =>
candidate.url().includes('/api/pokedexes/') && candidate.request().method() === 'PUT'
);
await modal.getByRole('button', { name: 'Save', exact: true }).click();
expect((await response).ok()).toBe(true);
await expect(modal).toHaveCount(0);
});
When('I cancel deleting {string}', async ({ page }, name: string) => {
const card = await dexCard(page, name);
page.once('dialog', (dialog) => dialog.dismiss());
await card.getByRole('button', { name: 'Delete' }).click();
});
When('I confirm deleting {string}', async ({ page }, name: string) => {
const card = await dexCard(page, name);
page.once('dialog', (dialog) => dialog.accept());
const response = page.waitForResponse(
(candidate) =>
candidate.url().includes('/api/pokedexes/') && candidate.request().method() === 'DELETE'
);
await card.getByRole('button', { name: 'Delete' }).click();
expect((await response).ok()).toBe(true);
});
When("I request the other trainer's Pokédex", async ({ page, state }) => {
const response = await page.request.get(`/api/pokedexes/${state.pokedexId}`);
state.lastResponseStatus = response.status();
});
Then('I see the empty Pokédex message', async ({ page }) => {
await expect(page.getByText("You haven't created any pokédexes yet!")).toBeVisible();
});
Then('I cannot create a Pokédex without a name and type', async ({ page }) => {
await expect(page.getByRole('button', { name: 'Create', exact: true })).toBeDisabled();
await expect(page.getByText('At least one type required')).toBeVisible();
});
Then('the Pokédex {string} is available to view', async ({ page }, name: string) => {
await expect((await dexCard(page, name)).getByRole('button', { name: 'View' })).toBeVisible();
});
Then('I am told that the Pokédex name is already used', async ({ state }) => {
expect(state.lastMessage).toMatch(/already have a Pokédex named/i);
});
Then('the Pokédex {string} is no longer listed', async ({ page }, name: string) => {
await page.goto('/my-pokedexes');
await expect(page.locator('.card').filter({ hasText: name })).toHaveCount(0);
});
Then('the Pokédex is not disclosed', async ({ state }) => {
expect(state.lastResponseStatus).toBe(404);
});
+113
View File
@@ -0,0 +1,113 @@
import { createBdd } from 'playwright-bdd';
import { test, expect } from '../fixtures';
import { firstPokemon, openFirstPokemon } from '../support/app';
const { When, Then } = createBdd(test);
async function ensurePokemonModal(page: Parameters<typeof firstPokemon>[0]) {
if ((await page.getByRole('dialog').count()) === 0) await openFirstPokemon(page);
}
async function settleAndReload(page: Parameters<typeof firstPokemon>[0]) {
await expect(page.getByText(/Saving…/)).toHaveCount(0, { timeout: 15_000 });
await page.reload({ waitUntil: 'networkidle' });
await expect(firstPokemon(page)).toBeVisible();
}
When('I mark the first Pokémon as caught', async ({ page }) => {
await ensurePokemonModal(page);
const checkbox = page
.getByRole('dialog')
.getByText('Caught:', { exact: true })
.locator('..')
.getByRole('checkbox');
await checkbox.check();
});
When('I mark the first Pokémon as needing evolution', async ({ page }) => {
await ensurePokemonModal(page);
const checkbox = page
.getByRole('dialog')
.getByText('Needs to evolve:', { exact: true })
.locator('..')
.getByRole('checkbox');
await checkbox.check();
});
When('I mark the first Pokémon as in HOME', async ({ page }) => {
await ensurePokemonModal(page);
await page
.getByRole('dialog')
.getByText('In Home:', { exact: true })
.locator('..')
.getByRole('checkbox')
.check();
});
When('I add the note {string} to the first Pokémon', async ({ page }, note: string) => {
await ensurePokemonModal(page);
await page.getByRole('dialog').getByLabel('Notes:').fill(note);
await page.getByRole('dialog').getByLabel('Notes:').blur();
});
When('I mark box {int} as caught', async ({ page }, box: number) => {
const heading = page.getByRole('heading', { name: `Box ${box}`, exact: true });
const container = heading.locator('..').locator('..');
await container.getByRole('button', { name: 'Open bulk actions menu' }).click();
await container.getByRole('button', { name: 'Mark box as Caught' }).click();
});
When('I filter to Pokémon that are not caught', async ({ page }) => {
if ((await page.getByRole('dialog').count()) > 0) {
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
}
await page.getByText('Not caught', { exact: true }).locator('..').getByRole('checkbox').check();
});
When('I select the {string} box layout', async ({ page }, layout: string) => {
await page.getByLabel('Choose box view layout density').selectOption(layout.toLowerCase());
});
When('I reload the Pokédex', async ({ page }) => {
await settleAndReload(page);
});
Then('the first Pokémon is shown as caught after reloading', async ({ page }) => {
await settleAndReload(page);
await expect(firstPokemon(page)).toHaveAttribute('aria-label', /Status: Caught/);
});
Then('the first Pokémon needs evolution and is not marked caught', async ({ page }) => {
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await settleAndReload(page);
await expect(firstPokemon(page)).toHaveAttribute('aria-label', /Needs to evolve/);
await expect(firstPokemon(page)).not.toHaveAttribute('aria-label', /Status: Caught(?:,|$)/);
});
Then('its HOME state and note persist after reloading', async ({ page }) => {
await page.getByRole('dialog').getByRole('button', { name: 'Close', exact: true }).click();
await settleAndReload(page);
await expect(firstPokemon(page)).toHaveAttribute('aria-label', /In HOME/);
await openFirstPokemon(page);
await expect(page.getByRole('dialog').getByLabel('Notes:')).toHaveValue(
'Caught, traded, and checked'
);
});
Then('box {int} contains {int} caught Pokémon', async ({ page }, _box: number, count: number) => {
await settleAndReload(page);
const firstBoxEntries = page
.getByRole('button', { name: /^View details for / })
.filter({ hasNot: page.locator('[disabled]') });
for (let index = 0; index < count; index++) {
await expect(firstBoxEntries.nth(index)).toHaveAttribute('aria-label', /Status: Caught/);
}
});
Then('the caught Pokémon is filtered out', async ({ page }) => {
await expect(firstPokemon(page)).toHaveAttribute('aria-disabled', 'true');
});
Then('the {string} box layout remains selected', async ({ page }, layout: string) => {
await expect(page.getByLabel('Choose box view layout density')).toHaveValue(layout.toLowerCase());
});
+55
View File
@@ -0,0 +1,55 @@
import { createBdd } from 'playwright-bdd';
import type { Page } from '@playwright/test';
import { test, expect } from '../fixtures';
const { Given, When, Then } = createBdd(test);
async function waitForServiceWorker(page: Page) {
return page.evaluate(async () => {
if (!('serviceWorker' in navigator)) throw new Error('Service workers are not supported');
const registration = await Promise.race([
navigator.serviceWorker.ready,
new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error('Service worker registration timed out')), 15_000)
)
]);
return registration.active?.scriptURL ?? null;
});
}
When('I open the built application', async ({ page }) => {
await page.goto('/');
await waitForServiceWorker(page);
});
Given('I have opened the built application online', async ({ page }) => {
await page.context().setOffline(false);
await page.goto('/');
await waitForServiceWorker(page);
await page.reload();
});
When('I go offline and revisit the home page with a trailing slash', async ({ page }) => {
await page.context().setOffline(true);
await page.goto('/', { waitUntil: 'domcontentloaded' });
});
When('I go offline and then return online', async ({ page }) => {
await page.context().setOffline(true);
await page.reload({ waitUntil: 'domcontentloaded' });
await page.context().setOffline(false);
await page.reload({ waitUntil: 'domcontentloaded' });
});
Then('a service worker controls the page', async ({ page }) => {
expect(await waitForServiceWorker(page)).toMatch(/\/(?:sw|prompt-sw)\.js$/);
});
Then('the application cache is present', async ({ page }) => {
const cacheNames = await page.evaluate(() => caches.keys());
expect(cacheNames.length).toBeGreaterThan(0);
});
Then('the application remains available', async ({ page }) => {
await expect(page.getByRole('heading', { name: /Start Your Pokédex Journey/ })).toBeVisible();
});
+116
View File
@@ -0,0 +1,116 @@
import type { Page } from '@playwright/test';
import type { ScenarioState } from '../fixtures';
const SUPABASE_URL = process.env.TEST_SUPABASE_URL ?? 'http://127.0.0.1:54321';
const SERVICE_ROLE_KEY = process.env.E2E_SERVICE_ROLE_KEY;
function requireServiceRoleKey(): string {
if (!SERVICE_ROLE_KEY) {
throw new Error('E2E_SERVICE_ROLE_KEY is required. Run BDD through "npm run test:bdd".');
}
return SERVICE_ROLE_KEY;
}
export async function createConfirmedUser(state: ScenarioState): Promise<void> {
if (state.userId) return;
const key = requireServiceRoleKey();
const response = await fetch(`${SUPABASE_URL}/auth/v1/admin/users`, {
method: 'POST',
headers: {
apikey: key,
Authorization: `Bearer ${key}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: state.email,
password: state.password,
email_confirm: true
})
});
if (!response.ok)
throw new Error(`Unable to create BDD user: ${response.status} ${await response.text()}`);
const body = (await response.json()) as { id: string };
state.userId = body.id;
}
export async function signIn(page: Page, state: ScenarioState, password = state.password) {
await page.goto('/signin');
await page.getByLabel('Email').fill(state.email);
await page.getByLabel('Password').fill(password);
await page.getByRole('button', { name: 'Sign In' }).click();
}
export async function createDexThroughUi(
page: Page,
state: ScenarioState,
options: { name: string; type: string; game?: string; dex?: string }
) {
await page.goto('/my-pokedexes');
await page
.getByRole('button', { name: /Create (New|Your First) Pokédex/ })
.first()
.click();
await page.getByLabel('Name').fill(options.name);
await page.getByText(options.type, { exact: false }).locator('..').getByRole('checkbox').check();
if (options.game) {
await page.getByLabel('Game Scope').selectOption({ label: options.game });
if (options.dex) {
const checkbox = page
.getByText(options.dex, { exact: false })
.locator('..')
.getByRole('checkbox');
if (!(await checkbox.isChecked())) await checkbox.check();
}
}
await page.locator('.modal-open').getByRole('button', { name: 'Create', exact: true }).click();
await page.waitForLoadState('networkidle');
state.pokedexName = options.name;
if (page.url().includes('/pokedex/')) {
state.pokedexId = page.url().split('/pokedex/')[1].split(/[?#]/)[0];
} else {
const card = page.locator('.card').filter({ hasText: options.name }).first();
await card.getByRole('button', { name: 'View', exact: true }).click();
await page.waitForURL('**/pokedex/**');
state.pokedexId = page.url().split('/pokedex/')[1].split(/[?#]/)[0];
}
}
export async function loadEntries(page: Page, state: ScenarioState, forms: boolean) {
if (!state.pokedexId) throw new Error('A Pokédex must be created before loading entries');
const result = await page.evaluate(
async ([id, enableForms]) => {
const response = await fetch(
`/api/pokedexes/${id}/combined-data?page=1&limit=9999&enableForms=${enableForms}`
);
if (!response.ok) throw new Error(await response.text());
const body = await response.json();
return body.combinedData.map(
(row: {
pokedexEntry: {
_id: string;
pokemon: string;
form: string | null;
pokedexNumber: number;
};
}) => ({
id: row.pokedexEntry._id,
pokemon: row.pokedexEntry.pokemon,
form: row.pokedexEntry.form,
num: row.pokedexEntry.pokedexNumber
})
);
},
[state.pokedexId, String(forms)]
);
state.entries = result;
}
export function firstPokemon(page: Page) {
return page.getByRole('button', { name: /^View details for / }).first();
}
export async function openFirstPokemon(page: Page) {
const pokemon = firstPokemon(page);
await pokemon.click();
await page.locator('.modal-open, [role="dialog"]').first().waitFor({ state: 'visible' });
}