Focus browser tests on visible behavior #82

Merged
eleith merged 1 commits from test/focus-browser-journeys into main 2026-11-24 15:28:59 +00:00
7 changed files with 250 additions and 652 deletions

No files matched your search

+129 -227
View File
@@ -1,150 +1,122 @@
import { expect, test, type Request } from '@playwright/test';
import { prepared, prepareReports, readPreparationTimestamp } from './cash-overview-fixture';
import { expect, test, type Page, type Request } from '@playwright/test';
import { prepared, prepareReports, waitForPreparationToSettle } from './cash-overview-fixture';
import { addOwnedJournalPart } from './owned-journal-part';
test('desktop account navigation preserves client routing and observes later saved registers', async ({
page,
context
}) => {
test('desktop Accounts links open the saved trend and account registers', async ({ page }) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.emulateMedia({ colorScheme: 'light' });
await prepared(page);
await page.goto('/settings');
const savedAt = await readPreparationTimestamp(page);
await page.goto('/');
const accounts = page.getByRole('complementary', { name: 'Accounts', exact: true });
const balanceDate = accounts.getByText(/^Balances as of/);
await expect(balanceDate).toBeVisible();
await expect(balanceDate.locator('time')).toHaveAttribute('datetime', '2026-04-16');
await expect(accounts.getByText('$8,520.00', { exact: true })).toBeVisible();
await expect(
accounts
.getByRole('region', { name: 'Net worth', exact: true })
.getByText('$11,825.00', { exact: true })
).toBeVisible();
await expect(accounts.getByRole('link', { name: /^Brokerage\b/ })).toBeVisible();
await expect(
accounts.getByRole('link', { name: /^assets:investments:retirement\b/ })
).toBeVisible();
// Cash uses the whole space beside the rail, not a centered reading column.
const main = page.locator('main');
const mainBox = await main.boundingBox();
const railBox = await accounts.boundingBox();
expect(mainBox).not.toBeNull();
expect(railBox).not.toBeNull();
expect(mainBox!.x).toBeCloseTo(0, 0);
expect(mainBox!.x + mainBox!.width).toBeCloseTo(railBox!.x, 0);
const header = page.getByRole('banner');
const headerBox = await header.boundingBox();
const accountsHeaderBox = await accounts.locator('header').boundingBox();
expect(headerBox!.height).toBeCloseTo(accountsHeaderBox!.height, 0);
expect(headerBox!.y + headerBox!.height).toBeCloseTo(
accountsHeaderBox!.y + accountsHeaderBox!.height,
0
);
await expect(
header.getByRole('link', { name: 'Home', exact: true }).locator('img')
).toBeVisible();
const main = page.getByRole('main');
// The Accounts total opens the saved trend rather than another Cash card.
const netWorthLink = accounts.getByRole('link', { name: /^Net worth/ });
await expect(netWorthLink).toHaveAttribute('href', '/reports/networth');
await netWorthLink.click();
await expect(page).toHaveURL(/\/reports\/networth$/);
const netWorth = accounts.getByRole('link', { name: /^Net worth/ });
await netWorth.click();
await expect(main.getByRole('heading', { name: 'Net worth', exact: true })).toBeVisible();
await expect(netWorthLink).toHaveAttribute('aria-current', 'page');
const period = page.getByRole('button', { name: 'Net worth period', exact: true });
const rows = page
.getByRole('table', { name: 'Net worth by valuation date', exact: true })
.locator('tbody tr');
await expect(period).toHaveText('3 months');
await expect(rows).toHaveCount(3);
await expect(rows.getByRole('rowheader')).toHaveText(['2026-02-28', '2026-03-31', '2026-04-16']);
for (const index of [0, 1]) {
await expect(rows.nth(index).getByRole('cell')).toHaveText([
'No reported amounts',
'No reported valuation'
]);
}
await expect(rows.last().getByRole('cell')).toHaveText([
'11825.00',
'USD',
'No unconverted units'
]);
const accountsText = await accounts.innerText();
const requests: string[] = [];
const observe = (request: Request) => {
if (
['fetch', 'xhr', 'document'].includes(request.resourceType()) ||
request.method() === 'POST'
) {
requests.push(`${request.method()} ${new URL(request.url()).pathname}`);
}
};
page.on('request', observe);
await page.evaluate(() => Object.assign(window, { netWorthNavigationToken: 'retained' }));
await period.click();
await page.getByRole('option', { name: '1 month', exact: true }).click();
await expect(page).toHaveURL(/\/reports\/networth\?months=1$/);
await expect(rows).toHaveCount(1);
await expect(netWorthLink).toHaveAttribute('aria-current', 'page');
await page.goBack();
await expect(period).toHaveText('3 months');
await expect(rows).toHaveCount(3);
expect(await accounts.innerText()).toBe(accountsText);
expect(await page.evaluate(() => Reflect.get(window, 'netWorthNavigationToken'))).toBe(
'retained'
);
expect(requests).toEqual([]);
page.off('request', observe);
await page.goto('/reports/networth?months=12');
await expect(period).toHaveText('12 months');
await expect(rows).toHaveCount(12);
await expect(rows.first().getByRole('rowheader')).toHaveText('2025-05-31');
await expect(rows.last().getByRole('rowheader')).toHaveText('2026-04-16');
await expect(netWorthLink).toHaveAttribute('aria-current', 'page');
await expect(netWorth).toHaveAttribute('aria-current', 'page');
await expect(
main.getByRole('table', { name: 'Net worth by valuation date' }).getByRole('row', {
name: /2026-04-16 11825\.00 USD/
})
).toBeVisible();
await accounts.getByRole('link', { name: /^Everyday checking\b/ }).click();
await expect(main.getByRole('heading', { name: 'Everyday checking', exact: true })).toBeVisible();
await accounts.getByRole('link', { name: /^Brokerage\b/ }).click();
await expect(main.getByRole('heading', { name: 'Brokerage', exact: true })).toBeVisible();
page.on('request', observe);
});
// Explicit work happens in another authenticated page, not in the page left open.
const preparationPage = await context.newPage();
let laterAt: string;
try {
laterAt = await prepareReports(preparationPage);
} finally {
await preparationPage.close();
}
expect(laterAt).not.toBe(savedAt);
expect(requests).toEqual([]);
page.off('request', observe);
test.describe('saved register refresh', () => {
let restoreBaseline: ((page: Page) => Promise<void>) | undefined;
// Query-only navigation retains component instances; the saved register must
// still refresh without a document reload.
const token = `account-navigation-${Date.now()}`;
await page.evaluate((value) => {
Object.assign(window, { accountNavigationToken: value });
}, token);
const accountPath = new URL(page.url()).pathname;
const refreshed = page.waitForResponse(
(response) =>
response.request().resourceType() === 'fetch' &&
new URL(response.url()).pathname.startsWith(accountPath)
);
await main
.getByRole('link', { name: 'Date: oldest first; show newest first', exact: true })
.click();
await expect(page).toHaveURL(/\/registers\/investments\/[a-z0-9]{8}\?order=desc$/);
const refreshedData = await refreshed;
expect(refreshedData.ok()).toBe(true);
// The publication stamp remains page data, not a register metadata wall.
expect(await refreshedData.text()).toContain(laterAt);
expect(await page.evaluate(() => Reflect.get(window, 'accountNavigationToken'))).toBe(token);
test.afterEach(async ({ page }, testInfo) => {
const restore = restoreBaseline;
restoreBaseline = undefined;
if (!restore) return;
testInfo.setTimeout(65_000);
await restore(page);
});
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(1440);
test('changing register order shows a newly prepared posting without reloading', async ({
page,
context
}) => {
const deployment = process.env.HLEDGER_TEST_DEPLOYMENT;
test.skip(
Boolean(process.env.PLAYWRIGHT_BASE_URL) || !deployment,
'Requires the owned browser journal.'
);
if (!deployment) return;
await waitForPreparationToSettle(page);
await prepared(page);
const accounts = page.getByRole('complementary', { name: 'Accounts', exact: true });
await accounts.getByRole('link', { name: /^Brokerage\b/ }).click();
const order = page.getByRole('link', {
name: 'Date: oldest first; show newest first',
exact: true
});
await expect(order).toBeVisible();
const brokerageURL = new URL(page.url());
brokerageURL.searchParams.set('order', 'desc');
const balanceDate = accounts.getByText(/^Balances as of/).locator('time');
await expect(balanceDate).toHaveAttribute('datetime', '2026-04-16');
const deposit = page.getByRole('button', {
name: 'Open investment activity: Deposit on 2026-04-17',
exact: true
});
await expect(deposit).toHaveCount(0);
await page.evaluate(() => Object.assign(window, { registerDocumentRetained: true }));
const requests: string[] = [];
const posts: string[] = [];
const observe = (request: Request) => {
const pathname = new URL(request.url()).pathname;
if (request.method() === 'POST') posts.push(pathname);
if (
['fetch', 'xhr', 'document'].includes(request.resourceType()) ||
request.method() === 'POST'
) {
requests.push(`${request.method()} ${pathname}`);
}
};
const removeDeposit = await addOwnedJournalPart(
deployment,
'navigation-deposit.journal',
`2026-04-17 Navigation fixture deposit
assets:investments:brokerage 23.47 USD
equity:opening
`
);
restoreBaseline = async (page) => {
// A timed-out attempt may still be working. Don't edit the journal or join that run.
await waitForPreparationToSettle(page);
await removeDeposit();
await prepareReports(page);
await page.goto(brokerageURL.href);
await expect(balanceDate).toHaveAttribute('datetime', '2026-04-16');
await expect(
page.getByRole('button', { name: 'Open investment activity: Buy BND on 2026-04-04' })
).toBeVisible();
await expect(deposit).toHaveCount(0);
};
page.on('request', observe);
const preparationPage = await context.newPage();
try {
await prepareReports(preparationPage);
} finally {
await preparationPage.close();
}
await expect(deposit).toHaveCount(0);
expect(requests).toEqual([]);
await order.click();
await expect(page).toHaveURL(brokerageURL.href);
await expect(deposit).toBeInViewport();
await expect(balanceDate).toHaveAttribute('datetime', '2026-04-17');
expect(await page.evaluate(() => Reflect.get(window, 'registerDocumentRetained'))).toBe(true);
expect(posts).toEqual([]);
});
});
test('desktop Accounts visibility survives layout navigation and resets on reload', async ({
@@ -152,20 +124,16 @@ test('desktop Accounts visibility survives layout navigation and resets on reloa
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await prepared(page);
await page.goto('/');
const accounts = page.getByRole('complementary', { name: 'Accounts', exact: true });
const toggle = page.getByRole('button', { name: 'Accounts', exact: true });
const drawer = page.getByRole('dialog', { name: 'Accounts', exact: true });
await expect(accounts).toBeVisible();
await expect(toggle).toBeEnabled();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
await toggle.focus();
await toggle.press('Enter');
await expect(accounts).not.toBeVisible();
await expect(toggle).toBeFocused();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await expect(drawer).not.toBeVisible();
await expect(page).toHaveURL(new URL('/registers/cash', page.url()).href);
await page
.getByRole('navigation', { name: 'Primary', exact: true })
@@ -173,7 +141,6 @@ test('desktop Accounts visibility survives layout navigation and resets on reloa
.click();
await expect(page).toHaveURL(/\/settings$/);
await expect(accounts).not.toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'false');
await page.setViewportSize({ width: 900, height: 900 });
await toggle.click();
await expect(drawer).toBeVisible();
@@ -181,149 +148,84 @@ test('desktop Accounts visibility survives layout navigation and resets on reloa
await expect(drawer).not.toBeVisible();
await page.setViewportSize({ width: 1440, height: 900 });
await expect(accounts).not.toBeVisible();
await toggle.focus();
await toggle.press('Enter');
await expect(accounts).toBeVisible();
await expect(toggle).toBeFocused();
await expect(drawer).not.toBeVisible();
await toggle.click();
await expect(accounts).not.toBeVisible();
await page.reload();
await expect(accounts).toBeVisible();
await expect(toggle).toHaveAttribute('aria-expanded', 'true');
});
test('responsive Accounts supports phone, overlay drawer and desktop transitions in dark mode', async ({
test('Accounts drawer preserves focus and client navigation across viewport changes', async ({
page
}) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.emulateMedia({ colorScheme: 'dark' });
await prepared(page);
const trigger = page.getByRole('button', { name: 'Accounts', exact: true });
const drawer = page.getByRole('dialog', { name: 'Accounts', exact: true });
await trigger.focus();
await page.keyboard.press('Enter');
await expect(drawer).toBeVisible();
const close = drawer.getByRole('button', { name: 'Close accounts', exact: true });
const main = page.getByRole('main');
await expect(trigger).toBeEnabled();
await trigger.press('Enter');
await expect(close).toBeFocused();
await expect(drawer).toBeInViewport({ ratio: 1 });
const phoneBox = await drawer.boundingBox();
expect(phoneBox!.x).toBeCloseTo(0, 0);
expect(phoneBox!.width).toBeCloseTo(390, 0);
await page.keyboard.press('Escape');
await expect(drawer).not.toBeVisible();
await expect(trigger).toBeFocused();
await page.keyboard.press('Enter');
await close.click();
await expect(drawer).not.toBeVisible();
await expect(trigger).toBeFocused();
await page.keyboard.press('Enter');
await expect(close).toBeFocused();
await page.setViewportSize({ width: 900, height: 844 });
await expect(drawer).toBeInViewport({ ratio: 1 });
const overlayBox = await drawer.boundingBox();
expect(overlayBox!.x).toBeGreaterThan(0);
expect(overlayBox!.x + overlayBox!.width).toBeCloseTo(900, 0);
await page.mouse.click(24, 200);
await expect(drawer).not.toBeVisible();
await expect(trigger).toBeFocused();
await trigger.click();
await drawer.getByRole('link', { name: /^Net worth/ }).click();
await expect(page).toHaveURL(/\/reports\/networth$/);
await expect(
page.locator('main').getByRole('heading', { name: 'Net worth', exact: true })
).toBeVisible();
const netWorth = drawer.getByRole('link', { name: /^Net worth/ });
await netWorth.click();
await expect(main.getByRole('heading', { name: 'Net worth', exact: true })).toBeVisible();
await expect(drawer).not.toBeVisible();
await trigger.click();
await expect(drawer.getByRole('link', { name: /^Net worth/ })).toHaveAttribute(
'aria-current',
'page'
);
// The current destination still refreshes saved reports; closing must not cancel it.
const refreshed = page.waitForResponse(
(response) =>
response.request().method() === 'GET' &&
new URL(response.url()).pathname === '/reports/networth/__data.json'
);
await drawer.getByRole('link', { name: /^Net worth/ }).focus();
await page.keyboard.press('Enter');
const refresh = await refreshed;
expect(refresh.status()).toBe(200);
// The app's afterNavigate focus confirms completion; don't wait on transport drain.
await expect(page).toHaveURL(/\/reports\/networth$/);
await expect(netWorth).toHaveAttribute('aria-current', 'page');
await netWorth.press('Enter');
await expect(drawer).not.toBeVisible();
await expect(page.locator('main')).toBeFocused();
await page
.getByRole('navigation', { name: 'Primary', exact: true })
.getByRole('link', { name: 'Home', exact: true })
.click();
await expect(
page.locator('main').getByRole('heading', { name: 'Cash', exact: true })
).toBeVisible();
await expect(main).toBeFocused();
await trigger.click();
await drawer.getByRole('link', { name: 'Investments', exact: true }).click();
await expect(page).toHaveURL(/\/registers\/investments$/);
await expect(
page.locator('main').getByRole('heading', { name: 'Investments', exact: true })
).toBeVisible();
await expect(drawer).not.toBeVisible();
await expect(main.getByRole('heading', { name: 'Investments', exact: true })).toBeVisible();
await trigger.click();
await expect(close).toBeFocused();
await page.goBack();
await expect(
page.locator('main').getByRole('heading', { name: 'Cash', exact: true })
).toBeVisible();
await expect(main.getByRole('heading', { name: 'Net worth', exact: true })).toBeVisible();
await expect(drawer).not.toBeVisible();
await expect(trigger).not.toBeFocused();
await page.setViewportSize({ width: 390, height: 844 });
await trigger.click();
await expect(close).toBeFocused();
const checking = drawer.getByRole('link', { name: /^Everyday checking\b/ });
await checking.focus();
await page.evaluate(() => Object.assign(window, { drawerNavigationToken: 'retained' }));
await page.keyboard.press('Enter');
await expect(
page.locator('main').getByRole('heading', { name: 'Everyday checking', exact: true })
).toBeVisible();
await page.evaluate(() => Object.assign(window, { drawerDocumentRetained: true }));
await drawer.getByRole('link', { name: /^Everyday checking\b/ }).press('Enter');
await expect(main.getByRole('heading', { name: 'Everyday checking', exact: true })).toBeVisible();
await expect(drawer).not.toBeVisible();
await expect(trigger).not.toBeFocused();
// Closing the portal must not turn its link into a full-document navigation.
expect(await page.evaluate(() => Reflect.get(window, 'drawerNavigationToken'))).toBe('retained');
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
expect(await page.evaluate(() => Reflect.get(window, 'drawerDocumentRetained'))).toBe(true);
// The account drawer must not leave the register's existing dialog unusable.
const activity = page.getByRole('region', { name: 'Cash register activity', exact: true });
const opener = activity.getByRole('button', { name: /^View transaction details:/ }).first();
await opener.click();
const details = page.getByRole('dialog', { name: 'Transaction details', exact: true });
await expect(details).toBeVisible();
await details.getByRole('button', { name: 'Close transaction details', exact: true }).click();
await expect(opener).toBeFocused();
await trigger.click();
await expect(drawer).toBeVisible();
await page.setViewportSize({ width: 1440, height: 900 });
await expect(drawer).not.toBeVisible();
await expect(page.getByRole('complementary', { name: 'Accounts', exact: true })).toBeVisible();
// Real focus and scrolling detect stale modal inertness/scroll locks, not CSS classes.
const dateOrder = page.locator('main').getByRole('link', { name: /^Date:/ });
const dateOrder = main.getByRole('link', { name: /^Date:/ });
await dateOrder.focus();
await expect(dateOrder).toBeFocused();
// Cash history deliberately fills the viewport and scrolls internally. Use a
// normal document page to verify that closing the drawer released its body lock.
// Cash history scrolls internally; use the overview to detect a stale body lock.
await page
.getByRole('navigation', { name: 'Primary', exact: true })
.getByRole('link', { name: 'Home', exact: true })
.click();
await expect(page.getByRole('heading', { name: 'Cash', exact: true, level: 1 })).toBeVisible();
const cashHeading = main.getByRole('heading', { name: 'Cash', exact: true, level: 1 });
await expect(cashHeading).toBeVisible();
expect(await page.evaluate(() => Reflect.get(window, 'drawerDocumentRetained'))).toBe(true);
await page.setViewportSize({ width: 1440, height: 350 });
await page.evaluate(() => window.scrollTo(0, 0));
await page.getByRole('heading', { name: 'Cash', exact: true, level: 1 }).hover();
await cashHeading.hover();
await page.mouse.wheel(0, 600);
await expect.poll(() => page.evaluate(() => window.scrollY)).toBeGreaterThan(0);
});
+15
View File
@@ -40,6 +40,21 @@ export async function prepareReports(page: Page): Promise<string> {
return preparedAt;
}
export async function waitForPreparationToSettle(page: Page) {
await page.goto('/settings');
const prepare = page.getByRole('button', { name: 'Prepare reports', exact: true });
const unreadable = page.getByText("Preparation status couldn't be read", { exact: false });
await expect
.poll(
async () => {
await page.reload();
return (await prepare.isEnabled()) && !(await unreadable.count());
},
{ timeout: 15_000 }
)
.toBe(true);
}
// Financial cases explicitly prepare only when there is no saved report.
export async function prepared(page: Page) {
await page.goto('/registers/cash');
+23 -249
View File
@@ -1,269 +1,43 @@
import { expect, test, type Request } from '@playwright/test';
import { expect, test } from '@playwright/test';
import { prepared } from './cash-overview-fixture';
import { historyRowCount } from './history-fixture';
test('Cash overview periods select one loaded snapshot and history without data requests', async ({
page,
request
}) => {
for (const [entry, destination] of [
['/', '/registers/cash'],
['/?months=6', '/registers/cash?months=6']
]) {
const redirect = await request.get(entry, { maxRedirects: 0 });
expect(redirect.status()).toBe(303);
expect(new URL(redirect.headers().location, redirect.url()).href).toBe(
new URL(destination, redirect.url()).href
);
}
await page.setViewportSize({ width: 1440, height: 900 });
test('Cash period and currency changes use saved data without a new request', async ({ page }) => {
await prepared(page);
await expect(page).toHaveURL(/\/registers\/cash$/);
await expect(page.getByRole('heading', { name: 'Cash', exact: true, level: 1 })).toBeVisible();
await expect(page.locator('main').getByText('Latest net worth', { exact: true })).toHaveCount(0);
await expect(
page.locator('main').getByRole('heading', { name: 'Accounts', exact: true })
).toHaveCount(0);
const controls = page.getByRole('button', { name: 'Cash overview period', exact: true });
const transactions = page
.getByText('Transactions', { exact: true })
.locator('..')
.getByRole('definition');
await expect(transactions).toHaveText((10 + historyRowCount).toLocaleString('en-US'));
const incomeRows = page
.getByRole('table', { name: 'Monthly income and spending', exact: true })
.locator('tbody tr');
await expect(controls).toHaveText('3 months');
await expect(incomeRows).toHaveCount(6);
await expect(incomeRows.nth(4).getByRole('rowheader')).toHaveText('2026-04');
await expect(incomeRows.nth(4).getByRole('cell')).toHaveText(['Income', '1000.00', 'USD']);
await expect(incomeRows.nth(5).getByRole('rowheader')).toHaveText('2026-04');
await expect(incomeRows.nth(5).getByRole('cell')).toHaveText(['Spending', '100.00', 'USD']);
await expect(
page.getByRole('img', { name: 'Income and spending by month in USD', exact: true })
).toBeVisible();
await expect(page.getByRole('region', { name: 'Journal summary', exact: true })).toHaveCount(0);
const categoryCard = page.getByRole('region', { name: 'Spending by category', exact: true });
const categoryCharts = categoryCard.getByRole('region', {
name: 'Spending by category charts',
exact: true
});
const categoryRows = categoryCard
.getByRole('table', { name: 'Spending by account', exact: true })
.locator('tbody tr');
const clothing = categoryRows.filter({
has: page.getByRole('rowheader', { name: 'expenses:clothing', exact: true })
});
const foreign = categoryRows.filter({
has: page.getByRole('rowheader', { name: 'expenses:foreign', exact: true })
});
const refund = categoryRows.filter({
has: page.getByRole('rowheader', { name: 'expenses:foreign-refund', exact: true })
});
const currency = categoryCard.getByRole('combobox', {
name: 'Spending chart currency',
exact: true
});
const chartValues = categoryCard.locator('#expense-categories-chart-values');
const usdChartValues = [
'expenses:travel: 50.00 USD',
'expenses:food: 20.00 USD',
'expenses:utilities: 10.00 USD',
'expenses:books: 8.00 USD',
'expenses:health: 6.00 USD',
'Other (grouped): 6.00 USD'
];
async function expectContainedCategoryChart(commodity = 'USD') {
await expect(
categoryCharts.getByRole('img', {
name: `Spending by category in ${commodity}`,
exact: true
})
).toBeVisible();
await expect(categoryCharts.getByRole('img')).toHaveCount(1);
await expect
.poll(() =>
categoryCharts.evaluate(
(node) => node.scrollHeight <= node.clientHeight && node.scrollWidth <= node.clientWidth
)
)
.toBe(true);
}
await expect(categoryRows).toHaveCount(7);
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
await expect(foreign).toHaveCount(0);
await expect(currency).toHaveCount(0);
await expectContainedCategoryChart();
const usdCanvas = categoryCharts.getByRole('img', {
name: 'Spending by category in USD',
exact: true
});
await expect(usdCanvas).toHaveAttribute('aria-describedby', 'expense-categories-chart-values');
await expect(chartValues).not.toBeVisible();
// The closed native disclosure still describes the plotted result for assistive technology.
await expect(usdCanvas).toHaveAccessibleDescription(usdChartValues.join(' '));
const summary = categoryCard.locator('summary', { hasText: /^Chart values$/ });
await summary.focus();
await summary.press('Enter');
await expect(chartValues).toBeVisible();
await expect(chartValues.getByRole('listitem')).toHaveText(usdChartValues);
const spendingAmounts = page
.getByRole('region', { name: 'Key figures', exact: true })
.getByText('Spending', { exact: true })
.locator('..')
.getByRole('listitem');
await expect(spendingAmounts).toHaveText(['$100.00']);
const accounts = page.getByRole('complementary', { name: 'Accounts', exact: true });
const accountsText = await accounts.innerText();
const period = page.getByRole('button', { name: 'Cash overview period', exact: true });
const spending = page.getByRole('region', { name: 'Spending by category', exact: true });
const currency = spending.getByRole('combobox', { name: 'Spending chart currency' });
const exactTable = spending.getByRole('table', { name: 'Spending by account' });
const refund = exactTable.getByRole('row', { name: /^expenses:foreign-refund\b/ });
await expect(period).toHaveText('3 months');
await expect(refund).toHaveCount(0);
const requests: string[] = [];
const observe = (request: Request) => {
page.on('request', (request) => {
if (
['fetch', 'xhr', 'document'].includes(request.resourceType()) ||
request.method() === 'POST'
) {
requests.push(`${request.method()} ${new URL(request.url()).pathname}`);
}
};
page.on('request', observe);
await page.evaluate(() => Object.assign(window, { periodNavigationToken: 'retained' }));
});
await controls.focus();
await controls.press('Enter');
await expect(page.getByRole('listbox')).toBeVisible();
await period.press('Enter');
await page.keyboard.press('End');
await page.keyboard.press('Enter');
await expect(page).toHaveURL(/\/registers\/cash\?months=12$/);
await expect(controls).toHaveText('12 months');
await expect(page.getByRole('listbox')).not.toBeVisible();
await expect(incomeRows).toHaveCount(24);
await expect(transactions).toHaveText((11 + historyRowCount).toLocaleString('en-US'));
await expect(controls).toBeFocused();
await expectContainedCategoryChart();
await expect(spendingAmounts).toHaveText(['€0.00', '$100.00']);
const januarySpending = incomeRows.filter({ hasText: '2026-01' }).filter({ hasText: 'Spending' });
await expect(januarySpending.getByRole('cell')).toHaveText(['Spending', '0.00', 'EUR']);
// One full native inventory: neither Top 5/Other nor chart currency filters this table.
await expect(categoryRows.getByRole('rowheader')).toHaveText([
'expenses:living',
'expenses:travel',
'expenses:food',
'expenses:utilities',
'expenses:books',
'expenses:health',
'expenses:clothing',
'expenses:foreign',
'expenses:foreign-refund'
]);
await expect(categoryRows.getByRole('cell')).toHaveText([
'2.00',
'USD',
'50.00',
'USD',
'20.00',
'USD',
'10.00',
'USD',
'8.00',
'USD',
'6.00',
'USD',
'4.00',
'USD',
'5.00',
'EUR',
'-5.00',
'EUR'
]);
await expect(currency).toHaveValue('USD');
await expect(currency.locator('option')).toHaveText(['USD', 'EUR']);
await expect(period).toHaveText('12 months');
await expect(period).toBeFocused();
await currency.selectOption('EUR');
await expectContainedCategoryChart('EUR');
await expect(usdCanvas).toHaveCount(0);
await expect(chartValues.getByRole('listitem')).toHaveText([
'expenses:foreign: 5.00 EUR',
'expenses:foreign-refund: -5.00 EUR'
]);
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
const chart = spending.getByRole('img', { name: 'Spending by category in EUR' });
await expect(chart).toHaveAccessibleDescription(/expenses:foreign-refund: -5\.00 EUR/);
await expect(refund.getByRole('cell')).toHaveText(['-5.00', 'EUR']);
const details = page.getByRole('region', { name: 'Income and spending details', exact: true });
await page.mouse.move(0, 0);
await expect(
details.locator('..').locator('[data-scroll-area-scrollbar][data-orientation="vertical"]')
).toBeVisible();
const tableHeading = details.locator('thead');
await details.focus();
const headingBefore = await tableHeading.boundingBox();
await page.keyboard.press('PageDown');
await expect.poll(() => details.evaluate((node) => node.scrollTop)).toBeGreaterThan(0);
const headingAfter = await tableHeading.boundingBox();
expect(headingAfter!.y).toBeCloseTo(headingBefore!.y, 0);
const clothing = exactTable.getByRole('row', { name: /^expenses:clothing\b/ });
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
// Leaving January removes EUR amounts altogether, not just their geometry.
await page.goBack();
await expect(controls).toHaveText('3 months');
await expect(incomeRows).toHaveCount(6);
await expect(transactions).toHaveText((10 + historyRowCount).toLocaleString('en-US'));
await expect(currency).toHaveCount(0);
await expectContainedCategoryChart();
await expect(chartValues.getByRole('listitem')).toHaveText(usdChartValues);
await expect(categoryRows).toHaveCount(7);
await expect(foreign).toHaveCount(0);
await expect(refund).toHaveCount(0);
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
await expect(spendingAmounts).toHaveText(['$100.00']);
await controls.press('Enter');
await expect(page.getByRole('option', { name: '3 months', exact: true })).toHaveAttribute(
'aria-selected',
'true'
);
await page.keyboard.press('Escape');
await expect(page.getByRole('listbox')).not.toBeVisible();
await expect(controls).toBeFocused();
await page.goForward();
await expect(controls).toHaveText('12 months');
await expect(currency.locator('option')).toHaveText(['USD', 'EUR']);
await expect(foreign.getByRole('cell')).toHaveText(['5.00', 'EUR']);
await currency.selectOption('USD');
await expectContainedCategoryChart();
await expect(chartValues.getByRole('listitem')).toHaveText(usdChartValues);
await expect(refund.getByRole('cell')).toHaveText(['-5.00', 'EUR']);
expect(await accounts.innerText()).toBe(accountsText);
expect(await page.evaluate(() => Reflect.get(window, 'periodNavigationToken'))).toBe('retained');
expect(requests).toEqual([]);
page.off('request', observe);
await page
.getByRole('navigation', { name: 'Primary', exact: true })
.getByRole('link', { name: 'Home', exact: true })
.click();
await expect(page).toHaveURL(/\/registers\/cash$/);
await expect(controls).toHaveText('3 months');
await expect(incomeRows).toHaveCount(6);
await page.goto('/?months=6');
await expect(page).toHaveURL(/\/registers\/cash\?months=6$/);
await expect(controls).toHaveText('6 months');
await expect(incomeRows).toHaveCount(12);
await expect(transactions).toHaveText((11 + historyRowCount).toLocaleString('en-US'));
await expectContainedCategoryChart();
await expect(spendingAmounts).toHaveText(['€0.00', '$100.00']);
await expect(januarySpending.getByRole('cell')).toHaveText(['Spending', '0.00', 'EUR']);
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
await expect(refund.getByRole('cell')).toHaveText(['-5.00', 'EUR']);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(1440);
await page.setViewportSize({ width: 390, height: 844 });
await page.emulateMedia({ colorScheme: 'dark' });
await expectContainedCategoryChart();
await expect(clothing.getByRole('cell')).toHaveText(['4.00', 'USD']);
await expect(foreign.getByRole('cell')).toHaveText(['5.00', 'EUR']);
await controls.click();
await expect(page.getByRole('option', { name: '12 months', exact: true })).toBeInViewport();
await page.keyboard.press('Escape');
await expect(controls).toBeFocused();
await expect(page.getByRole('region', { name: 'Key figures', exact: true })).toBeVisible();
await expect(
page.getByRole('table', { name: 'Monthly income and spending', exact: true })
).toBeVisible();
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
await expect(period).toHaveText('3 months');
await expect(refund).toHaveCount(0);
expect(requests).toEqual([]);
});
+9 -67
View File
@@ -1,10 +1,8 @@
import { expect, test } from '@playwright/test';
import { prepared } from './cash-overview-fixture';
test('opens the prepared investment snapshot and its exact value history without running a report', async ({
page
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
test('reads the saved investment value and its exact history on a phone', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await prepared(page);
const posts: string[] = [];
page.on('request', (request) => {
@@ -13,72 +11,16 @@ test('opens the prepared investment snapshot and its exact value history without
await page.goto('/registers/investments');
const main = page.getByRole('main');
await expect(main.getByRole('heading', { name: 'Investments', exact: true })).toBeVisible();
await expect(main.locator('header time')).toHaveAttribute('datetime', '2026-04-16');
const snapshot = main.getByRole('region', { name: 'Investment snapshot', exact: true });
await expect(snapshot.getByText('$3,305.00', { exact: true })).toBeVisible();
await expect(snapshot.getByText('2', { exact: true })).toBeVisible();
await expect(main.getByRole('img', { name: 'Portfolio value by reporting date' })).toBeVisible();
const securitiesChart = main.getByRole('img', { name: 'Portfolio by market value in USD' });
await expect(securitiesChart).toBeVisible();
const securitiesCard = main.getByRole('region', {
name: 'Portfolio by market value',
exact: true
const history = main.getByRole('region', { name: 'Portfolio value history details' });
const asOfRow = history.getByRole('row').filter({
has: page.locator('time[datetime="2026-04-16"]')
});
const historyCard = main.getByRole('region', { name: 'Portfolio value history', exact: true });
const securityValues = securitiesCard.getByRole('table', { name: 'Portfolio by market value' });
await expect(securityValues.getByRole('rowheader')).toHaveText(['VTI', 'BND', 'Cash']);
await expect(securityValues.getByRole('cell')).toHaveText(['2700.00', '405.00', '200.00']);
await expect
.poll(async () => {
const securities = await securitiesCard.boundingBox();
const history = await historyCard.boundingBox();
return (
securities !== null &&
history !== null &&
history.x >= securities.x + securities.width &&
Math.abs(securities.height - history.height) < 1
);
})
.toBe(true);
await page.setViewportSize({ width: 390, height: 844 });
await expect
.poll(async () => {
const securities = await securitiesCard.boundingBox();
const history = await historyCard.boundingBox();
const table = await securityValues.boundingBox();
const chart = await securitiesChart.boundingBox();
const pageFits = await page.evaluate(
() => document.documentElement.scrollWidth <= document.documentElement.clientWidth
);
return (
securities !== null &&
history !== null &&
table !== null &&
chart !== null &&
pageFits &&
chart.x >= securities.x &&
chart.x + chart.width <= securities.x + securities.width &&
history.y >= securities.y + securities.height &&
securities.x >= 0 &&
securities.x + securities.width <= 390 &&
table.x >= securities.x &&
table.x + table.width <= securities.x + securities.width
);
})
.toBe(true);
await expect(securitiesChart).toBeVisible();
await expect(securityValues.getByRole('cell', { name: '2700.00', exact: true })).toBeVisible();
const rows = historyCard.locator('tbody tr');
await expect(rows).toHaveCount(6);
await expect(rows.first().getByRole('cell')).toHaveText('Not available');
await expect(rows.last().locator('time')).toHaveAttribute('datetime', '2026-04-16');
await expect(rows.last().getByRole('cell')).toHaveText('3305.00 USD');
const details = historyCard.getByRole('region', { name: 'Portfolio value history details' });
await details.focus();
await expect(asOfRow.getByRole('cell')).toHaveText('3305.00 USD');
await history.focus();
await page.keyboard.press('End');
await expect(rows.last()).toBeInViewport();
await expect(details.getByRole('columnheader', { name: 'Date' })).toBeInViewport();
await expect(main.getByRole('link', { name: 'Holdings', exact: true })).toHaveCount(0);
await expect(main.getByRole('link', { name: /Brokerage/ })).toHaveCount(0);
await expect(asOfRow).toBeInViewport();
expect(posts).toEqual([]);
});
-58
View File
@@ -1,58 +0,0 @@
import { expect, test } from '@playwright/test';
import { readFile } from 'node:fs/promises';
test.use({ storageState: { cookies: [], origins: [] }, javaScriptEnabled: false });
test('publishes fixed Open Graph metadata and bundled images without authentication', async ({
page,
request,
baseURL
}) => {
await page.goto('/signin');
await expect(page.locator('meta[property="og:title"]')).toHaveAttribute(
'content',
'hledger reports'
);
await expect(page.locator('link[rel="icon"]')).toHaveJSProperty(
'href',
new URL('/images/favicon.ico', baseURL!).href
);
for (const filename of ['favicon.ico', 'app-icon.png']) {
const asset = await request.get(`/images/${filename}`, { maxRedirects: 0 });
expect(asset.status()).toBe(200);
expect(asset.headers()['content-type']).toMatch(/^image\//);
expect(await asset.body()).toEqual(
await readFile(new URL(`../static/images/${filename}`, import.meta.url))
);
}
const imageURL = new URL('/images/open-graph.png', baseURL!).href;
await expect(page.locator('meta[property="og:image"]')).toHaveAttribute('content', imageURL);
await expect(page.locator('meta[property="og:url"]')).toHaveAttribute(
'content',
new URL('/', baseURL!).href
);
await expect(page.locator('meta[property="og:image:width"]')).toHaveAttribute('content', '1200');
await expect(page.locator('meta[property="og:image:height"]')).toHaveAttribute('content', '630');
const image = await request.get(imageURL, { maxRedirects: 0 });
expect(image.status()).toBe(200);
expect(image.headers()['content-type']).toBe('image/png');
const bytes = await image.body();
expect(bytes).toEqual(
await readFile(new URL('../static/images/open-graph.png', import.meta.url))
);
expect(bytes.subarray(0, 8)).toEqual(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
expect(bytes.readUInt32BE(16)).toBe(1200);
expect(bytes.readUInt32BE(20)).toBe(630);
const head = await request.head(imageURL, { maxRedirects: 0 });
expect(head.status()).toBe(200);
expect(head.headers()['content-type']).toBe('image/png');
expect(await head.body()).toHaveLength(0);
const protectedPage = await request.get('/', {
maxRedirects: 0,
headers: { accept: 'text/html' }
});
expect(protectedPage.status()).toBe(303);
expect(protectedPage.headers()['location']).toBe('/signin');
});
+26
View File
@@ -0,0 +1,26 @@
import { lstat, readFile, unlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
export async function addOwnedJournalPart(deployment: string, name: string, contents: string) {
const root = resolve(deployment);
if (
process.env.PLAYWRIGHT_BASE_URL ||
dirname(root) !== resolve(tmpdir()) ||
!/^hledger-browser-[0-9a-f-]{36}$/.test(basename(root))
)
throw new Error('Adding a journal part requires an owned temporary browser deployment.');
if (!/^[a-z-]+\.journal$/.test(name)) throw new Error('Invalid journal part filename.');
for (const path of [root, join(root, 'journal'), join(root, 'journal', 'parts')]) {
if (!(await lstat(path)).isDirectory()) throw new Error('Invalid fixture directory.');
}
const marker = join(root, '.fixture');
if (
!(await lstat(marker)).isFile() ||
(await readFile(marker, 'utf8')) !== 'hledger-browser-fixture\n'
)
throw new Error('Missing fixture ownership marker.');
const path = join(root, 'journal', 'parts', name);
await writeFile(path, contents, { flag: 'wx', mode: 0o600 });
return () => unlink(path);
}
+48 -51
View File
@@ -1,29 +1,26 @@
import { lstat, readFile, unlink, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { basename, dirname, join, resolve } from 'node:path';
import { expect, test } from '@playwright/test';
import { prepareReports } from './cash-overview-fixture';
import { expect, test, type Page } from '@playwright/test';
import { prepareReports, waitForPreparationToSettle } from './cash-overview-fixture';
import { addOwnedJournalPart } from './owned-journal-part';
async function addInvalidPosting(deployment: string) {
const root = resolve(deployment);
if (
dirname(root) !== resolve(tmpdir()) ||
!/^hledger-browser-[0-9a-f-]{36}$/.test(basename(root))
)
throw new Error('Report recovery requires an owned temporary deployment.');
for (const path of [root, join(root, 'journal'), join(root, 'journal', 'parts')]) {
if (!(await lstat(path)).isDirectory()) throw new Error('Invalid fixture directory.');
}
const marker = join(root, '.fixture');
if (
!(await lstat(marker)).isFile() ||
(await readFile(marker, 'utf8')) !== 'hledger-browser-fixture\n'
)
throw new Error('Missing fixture ownership marker.');
const path = join(root, 'journal', 'parts', 'failed-update.journal');
await writeFile(path, 'Fictional invalid directive\n', { flag: 'wx', mode: 0o600 });
return () => unlink(path);
}
const failedUpdateWarning = (page: Page) =>
page.getByRole('status').filter({ hasText: 'Report update failed' });
const aprilIncome = (page: Page) =>
page.getByRole('table', { name: 'Monthly income and spending' }).getByRole('row', {
name: /2026-04 Income 1000\.00 USD/
});
let removeInvalidPart: (() => Promise<void>) | undefined;
test.afterEach(async ({ page }, testInfo) => {
const remove = removeInvalidPart;
removeInvalidPart = undefined;
if (!remove) return;
testInfo.setTimeout(65_000);
await waitForPreparationToSettle(page);
await remove();
await prepareReports(page);
await expect(aprilIncome(page)).toBeVisible();
await expect(failedUpdateWarning(page)).toHaveCount(0);
});
test('keeps the saved report readable with one warning until an explicit update succeeds', async ({
page
@@ -34,32 +31,32 @@ test('keeps the saved report readable with one warning until an explicit update
'Requires the owned browser journal.'
);
if (!deployment) return;
await waitForPreparationToSettle(page);
await prepareReports(page);
await page.goto('/settings');
const restore = await addInvalidPosting(deployment);
try {
await page.getByRole('button', { name: 'Prepare reports', exact: true }).click();
const status = page.getByRole('region', { name: 'Preparation status' });
const warning = page.getByRole('status').filter({ hasText: 'Report update failed' });
await expect(async () => {
await page.reload();
await expect(status.getByRole('alert')).toContainText('didn’t replace the saved report', {
timeout: 400
});
}).toPass({ timeout: 20_000 });
await expect(warning).toHaveCount(0);
await page.getByRole('link', { name: 'Browse reports', exact: true }).click();
await expect(warning).toHaveCount(1);
await expect(warning.locator('time')).toHaveAttribute('datetime', '2026-04-16');
await expect(page.getByRole('table', { name: 'Monthly income and spending' })).toContainText(
'1000.00'
);
await warning.getByRole('link', { name: 'Settings' }).click();
await expect(status.getByRole('alert')).toContainText('didn’t replace the saved report');
await expect(warning).toHaveCount(0);
} finally {
await restore();
}
await prepareReports(page);
await expect(page.getByRole('status').filter({ hasText: 'Report update failed' })).toHaveCount(0);
removeInvalidPart = await addOwnedJournalPart(
deployment,
'failed-update.journal',
'Fictional invalid directive\n'
);
const prepare = page.getByRole('button', { name: 'Prepare reports', exact: true });
await prepare.click();
const status = page.getByRole('region', { name: 'Preparation status' });
const warning = failedUpdateWarning(page);
await expect(async () => {
await page.reload();
await expect(status.getByRole('alert')).toContainText('didn’t replace the saved report', {
timeout: 400
});
await expect(prepare).toBeEnabled({ timeout: 400 });
}).toPass({ timeout: 20_000 });
await expect(warning).toHaveCount(0);
await page.getByRole('link', { name: 'Browse reports', exact: true }).click();
await expect(warning).toHaveCount(1);
await expect(warning.locator('time')).toHaveAttribute('datetime', '2026-04-16');
await expect(aprilIncome(page)).toBeVisible();
await warning.getByRole('link', { name: 'Settings' }).click();
await expect(status.getByRole('alert')).toContainText('didn’t replace the saved report');
await expect(warning).toHaveCount(0);
// The teardown explicitly retries the preparation and verifies the warning clears.
});