Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .agents/skills/writing-tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ Read `docs/frontend/testing.md` before you write one. Then do these steps:
3. In `frontend/tests/features/<feature>/`, add or extend three files: `*.locators.ts`, `*.tasks.ts`, and `*.spec.ts`.
4. Mock each call before the action that causes it. For each value that the page sends (a query parameter, a header, or a body field), read the request back with `api.last`.
5. If a test needs a signed-in user, add `test.use({ actor: as.user('Name') })`.
6. Run `pnpm test:e2e --repeat-each=10`. All runs must pass.
6. Run `pnpm test:e2e`. Then run `pnpm test:e2e --only-changed=main --repeat-each=10`. It runs 10 times each spec that differs from `main`, and each spec that imports a file that differs. All runs must pass. A flaky wait can pass one run, and no lint finds each one.
7. Make the test fail once on purpose. Remove the code that the test protects, and make sure that the test fails. Then put the code back.

Obey these rules:
Expand Down
10 changes: 6 additions & 4 deletions docs/frontend/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ A mock is a `MockRoute`: a plain object with a method, a full path, a status, an
The `api` fixture applies to each test automatically:

- It answers each request from the mocks of the test. A later mock wins over an earlier one, so a test can change an answer in the middle of a scenario.
- `api.hold(...routes)` is `api.mock` with answers that wait until the test calls the function that it returns. Use it to act or assert while an answer is on the way. The test does not depend on a time, as it does with `delayMs`.
- `api.hold(...routes)` is `api.mock` with answers that wait until the test calls the function that it returns. Use it to act or assert while an answer is on the way, so that the test does not depend on a time. A `MockRoute` has no delay.
- `api.holdPageSource(file)` holds the source file of a page in the same way, so that the navigation to that page stays in progress. Call it after the first open of the app, because a hold before that open blocks the app until the 30 s timeout. The URL changes at the start of a navigation, and the old page stays on the screen until the source file of the next page loads. So a test that must be on the next page waits for something on that page, not for the URL.
- `api.failPageSource(file)` aborts each request for the source file of a page, as a lost connection does, until the test calls the function that it returns. Match the chunk of the page component, such as `/\/assets\/about-[\w-]+\.js$/`. The build names each chunk after its module. A failure of this chunk stops the page, not the app. The router reloads the page once for a failed source file, so the test waits for the message of the app, not for the URL.
- It records each request that it answers. Read a request back with `api.last(method, path)` or `api.all(method, path)`.
Expand All @@ -97,7 +97,9 @@ test.use({ actor: as.userWithNoTenant('Ada Lovelace') })

For an anonymous visitor, use `as.anonymous()`. Then `/bff/user` answers 204, and the SPA goes to the login before it shows a page. Thus a spec of a page needs a signed-in actor. The session spec (`tests/features/session/session.spec.ts`) covers the anonymous visitor and a failed check of the session.

Login and logout leave the SPA. The browser goes to `/bff/login` or `/bff/logout`. Mock these with `bffApi.loginOpens()` and `bffApi.logoutOpens()`, and read the query of the request back. In a task, wait for the answer of `/bff/login`, and then assert the URL. Do not start with `toHaveURL` or `expect.poll`, because on a slow machine the server can take more than the 5 s of an assertion to serve the app before the SPA checks the session. Do not use `page.waitForURL` for the login, because in a development build React StrictMode starts the login twice, so the first navigation can abort, and `waitForURL` then fails. See `openLinkAndGoToLogin` in `tests/features/invites/invites.tasks.ts`.
Login and logout leave the SPA. The browser goes to `/bff/login` or `/bff/logout`. Mock these with `bffApi.loginOpens()` and `bffApi.logoutOpens()`, and read the query of the request back. In a task, wait for the answer of `/bff/login`, and then assert the URL. Do not start with `toHaveURL` or `expect.poll`, because on a slow machine the server can take more than the 5 s of an assertion to serve the app before the SPA checks the session. Do not use `page.waitForURL` for the login, because in a development build React StrictMode starts the login twice, so the first navigation can abort, and `waitForURL` then fails. To open a URL that goes to the login, call `openAndWaitForLogin(page, url)` from `tests/support/answers.ts`. For a click that goes to the login, see `submitAndGoToLogin` in `tests/features/invites/invites.tasks.ts`.

Check: `pnpm lint` fails on `waitUntil: 'commit'` in each file of `tests/`, because a navigation that waits only for the commit leaves the load of the app to the next expect.

### Builders

Expand All @@ -124,7 +126,7 @@ The workshop builder gives each status the actions that a caller with `manage_wo
- Import `test` and `expect` from `@tests/support/fixtures`, not from `@playwright/test`.
- Do not use `page.waitForTimeout`, retries, or `test.only`.

Check: `pnpm lint` fails when a `*.spec.ts` file calls a selector (`locator`, `getByRole`, and the other `getBy` calls), a `page.waitFor` call, `setTimeout`, or `test.only` (also `test.describe.only`), or imports `test` or `expect` from `@playwright/test`. It fails on `waitForTimeout` in each file of `tests/`. The rules are in `frontend/eslint.config.js`. No check finds a wait in a locators file, and no check reads the three parts of a spec.
Check: `pnpm lint` fails when a `*.spec.ts` file calls a selector (`locator`, `getByRole`, and the other `getBy` calls), a `page.waitFor` call, `setTimeout`, or `test.only` (also `test.describe.only`), or imports `test` or `expect` from `@playwright/test`. It fails on `waitForTimeout` and on a `timeout` option, such as `toBeVisible({ timeout: 2000 })`, in each file of `tests/`. In each file of `tests/` and `e2e/`, it fails on a wait that starts after the action: an `await` of `waitForResponse`, `waitForRequest`, `waitForEvent`, or a function that is not async and gives a Playwright `Response` or `Request`, such as `answered(...)`, and such a wait in a `const` that the next statement awaits. To count each answer of a read that runs again, give the number of the answer to one wait, as `answered` in `invites.tasks.ts` does, and do not await one wait after the other. The rules are in `frontend/eslint.config.js`. No check finds a wait in a locators file, and no check reads the three parts of a spec.

### Selectors

Expand Down Expand Up @@ -178,4 +180,4 @@ Each functional test runs in the `pago-pago` project. A test tagged `@zone` also

1. Write a builder for each new type, and an API file for each new area.
2. Write the locators file, the tasks file, and a spec that opens the page.
3. Run `pnpm test:e2e`. Run `pnpm test:e2e --repeat-each=10` before you push, to find a flaky test.
3. Run `pnpm test:e2e`. Before you push, run `pnpm test:e2e --only-changed=main --repeat-each=10` to find a flaky test. It runs 10 times each spec that differs from `main`, and each spec that imports a file that differs.
10 changes: 3 additions & 7 deletions frontend/e2e/auth-flows.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,16 +369,12 @@ test.describe(`Swagger - ${currentIdp.name}`, () => {

// Step 5: Login at the IDP
await popup.waitForLoadState('networkidle', { timeout: 15000 })
const closed = popup.waitForEvent('close', { timeout: 30000 }).then(() => true, () => false)
await loginAtIdp(popup, currentIdp)

// Step 6: Wait for popup to close
try {
await popup.waitForEvent('close', { timeout: 30000 })
} catch {
// Popup might have already closed or redirected
if (!popup.isClosed()) {
await popup.close()
}
if (!(await closed) && !popup.isClosed()) {
await popup.close()
}

// Step 7: Close the modal
Expand Down
67 changes: 66 additions & 1 deletion frontend/eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,62 @@ export const noPageActionRule = {
},
}

// docs/frontend/testing.md, section "Locators, tasks, and specs".
const waitMethods = /^waitFor(Response|Request|Event)$/
export const lateWaitMessage = 'This wait starts after the action before it, so it misses an answer or an event that came first. Arm the wait before the action, and await it after the action: `const answer = answered(...)`, then the action, then `await answer`.'

export const armWaitFirstRule = {
meta: { type: 'problem', schema: [], messages: { late: lateWaitMessage } },
create(context) {
const services = context.sourceCode.parserServices
const checker = services.program.getTypeChecker()
const isWaitMethod = (callee) => callee.type === 'MemberExpression' && waitMethods.test(callee.property.name)
const isAllOfWaits = (node) => {
const { callee, arguments: [list] } = node
return callee.type === 'MemberExpression' && callee.object.name === 'Promise' && callee.property.name === 'all'
&& list?.type === 'ArrayExpression' && list.elements.length > 0 && list.elements.every(isWait)
}
const armsItsOwnWait = (callee) => {
let symbol = checker.getSymbolAtLocation(services.esTreeNodeToTSNodeMap.get(callee.type === 'MemberExpression' ? callee.property : callee))
if (symbol && symbol.flags & ts.SymbolFlags.Alias)
symbol = checker.getAliasedSymbol(symbol)
const declaration = symbol?.declarations?.[0]
const fn = declaration && ts.isVariableDeclaration(declaration) ? declaration.initializer : declaration
return Boolean(fn && ts.isFunctionLike(fn) && fn.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.AsyncKeyword))
}
const givesPlaywrightAnswer = (node) => {
const type = services.getTypeAtLocation(node)
const answer = checker.getAwaitedType(type)
return answer !== undefined && answer !== type && isPlaywright(answer, ['Response', 'Request'])
}
function isWait(node) {
if (node?.type !== 'CallExpression')
return false
if (isAllOfWaits(node) || isWaitMethod(node.callee))
return true
return !armsItsOwnWait(node.callee) && givesPlaywrightAnswer(node)
}
const awaitedByNextStatement = (declaration, name) => {
const body = declaration.parent.body
const next = Array.isArray(body) ? body[body.indexOf(declaration) + 1] : undefined
const value = next?.type === 'ExpressionStatement'
? next.expression
: next?.type === 'VariableDeclaration' && next.declarations.length === 1 ? next.declarations[0].init : null
return value?.type === 'AwaitExpression' && value.argument.type === 'Identifier' && value.argument.name === name
}
return {
AwaitExpression(node) {
if (isWait(node.argument))
context.report({ node, messageId: 'late' })
},
'VariableDeclaration > VariableDeclarator'(node) {
if (node.id.type === 'Identifier' && isWait(node.init) && awaitedByNextStatement(node.parent, node.id.name))
context.report({ node, messageId: 'late' })
},
}
},
}

const within = (inner, outer) => inner.range[0] >= outer.range[0] && inner.range[1] <= outer.range[1]

const referencesIn = (sourceCode, node) => {
Expand Down Expand Up @@ -408,6 +464,14 @@ const testFileRules = [
selector: "CallExpression[callee.property.name='waitForTimeout']",
message: 'Do not wait for a time. In the *.tasks.ts file of the feature, wait for the response of the request, or let an expect retry until the state shows.',
},
{
selector: "Property[key.name='waitUntil'][value.value='commit']",
message: 'A navigation that waits only for the commit leaves the load of the app to the next expect, and its 5 s are too short on a slow machine. To open a URL that goes to the login, call openAndWaitForLogin(page, url) from @tests/support/answers. It waits for the answer of the login.',
},
{
selector: "CallExpression > ObjectExpression > Property[key.name='timeout']",
message: 'Do not set a timeout. A short one fails on a slow machine, and a long one guesses how slow the machine is. Wait for the event that ends the work: arm a wait for its answer before the action, or hold the answer with api.hold and answer it at the step that needs it.',
},
]

const specFileRules = [
Expand Down Expand Up @@ -497,7 +561,8 @@ export default tseslint.config(
languageOptions: {
parserOptions: { project: './tsconfig.tests.json', tsconfigRootDir: import.meta.dirname },
},
plugins: { playwright: { rules: { 'no-page-action': noPageActionRule } } },
plugins: { playwright: { rules: { 'no-page-action': noPageActionRule, 'arm-wait-first': armWaitFirstRule } } },
rules: { 'playwright/arm-wait-first': 'error' },
},
{
files: ['tests/**/*.ts'],
Expand Down
64 changes: 63 additions & 1 deletion frontend/eslint.config.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ESLint, Linter } from 'eslint'
import tseslint from 'typescript-eslint'
import { describe, expect, it } from 'vitest'
import { codeToWordsRules, noPageActionRule, serverStatePlugin, stringSelectorMessage } from './eslint.config.js'
import { armWaitFirstRule, codeToWordsRules, lateWaitMessage, noPageActionRule, serverStatePlugin, stringSelectorMessage } from './eslint.config.js'

const pageAction = "import type { Page } from '@playwright/test'\nexport const save = (page: Page) => page.click('#save')\n"

Expand Down Expand Up @@ -40,6 +40,68 @@ describe('playwright/no-page-action', { timeout: 60_000 }, () => {
})
})

async function lateWaitLines(body) {
const eslint = new ESLint({
cwd: import.meta.dirname,
overrideConfigFile: true,
overrideConfig: {
files: ['tests/**/*.ts'],
languageOptions: {
parser: tseslint.parser,
parserOptions: { project: './tsconfig.tests.json', tsconfigRootDir: import.meta.dirname, disallowAutomaticSingleRunInference: true },
},
plugins: { playwright: { rules: { 'arm-wait-first': armWaitFirstRule } } },
rules: { 'playwright/arm-wait-first': 'error' },
},
})
const code = `import type { Page, Request } from '@playwright/test'
export async function task(page: Page) {
const answered = (path: string) => page.waitForResponse((r) => new URL(r.url()).pathname === path)
const follow = async (): Promise<Request> => {
const sent = page.waitForRequest('**/next')
await page.click('#next')
return sent
}
${body}
}
`
const [result] = await eslint.lintText(code, { filePath: 'tests/support/fixtures.ts' })
expect(result.messages.every((message) => message.message === lateWaitMessage)).toBe(true)
return result.messages.map((message) => message.line - 8)
}

describe('playwright/arm-wait-first', { timeout: 60_000 }, () => {
it('reports a wait that starts after the action', async () => {
const lines = await lateWaitLines(` await page.reload()
await page.waitForResponse('**/api')
await answered('/api')
await page.waitForEvent('load')
await Promise.all([answered('/a'), answered('/b')])`)

expect(lines).toEqual([2, 3, 4, 5])
})

it('reports a wait that the next statement awaits, with no action between', async () => {
const lines = await lateWaitLines(` const answer = answered('/api')
await answer
const loaded = page.waitForEvent('load')
const page2 = await loaded`)

expect(lines).toEqual([1, 3])
})

it('takes a wait armed before the action, a wait in a Promise.all with the action, an async action, and a goto', async () => {
const lines = await lateWaitLines(` const answer = answered('/api')
await page.reload()
await answer
await Promise.all([answered('/api'), page.reload()])
await follow()
await page.goto('/')`)

expect(lines).toEqual([])
})
})

function serverStateMessages(code, file = 'src/domain/records/record.tsx') {
const linter = new Linter({ configType: 'flat' })
const rules = Object.keys(serverStatePlugin.rules).map((name) => [`server-state/${name}`, 'error'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,8 @@ test.describe('a signed-in user', () => {
})

test.describe('the loading placeholders', () => {
const slowList = { ...weatherApi.listReturns(aForecast()), delayMs: 2_000 }

test('hold still for a user who asks for reduced motion', async ({ page, api }) => {
api.mock(slowList)
api.hold(weatherApi.listReturns(aForecast()))
const weather = weatherForecastPage(page)

await weather.openWhileLoading()
Expand All @@ -147,7 +145,7 @@ test.describe('the loading placeholders', () => {
test.use({ reducedMotion: 'no-preference' })

test('pulse', async ({ page, api }) => {
api.mock(slowList)
api.hold(weatherApi.listReturns(aForecast()))
const weather = weatherForecastPage(page)

await weather.openWhileLoading()
Expand Down
12 changes: 7 additions & 5 deletions frontend/tests/features/invites/invites.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,13 +188,15 @@ test.describe('the invites of a tenant admin', () => {
})

test('creates one invite when the second Enter comes before a render of the first', { tag: '@INV-2' }, async ({ page, api }) => {
api.mock(invitesApi.listReturns([]), { ...invitesApi.creates(anInvite(), token), delayMs: 300 })
api.mock(invitesApi.listReturns([]))
const answer = api.hold(invitesApi.creates(anInvite(), token))
const users = usersWithInvites(page)
await users.openWithList()
await users.openDialog()
await users.at.emailField.fill('new@example.com')

await users.pressEnterTwiceBeforeARender()
answer()

await expect(users.at.linkField).toBeVisible()
expect(api.all('post', invitesPaths.list)).toHaveLength(1)
Expand Down Expand Up @@ -232,9 +234,9 @@ test.describe('the invites of a tenant admin', () => {
const users = usersWithInvites(page)
await users.openWithList()
await users.openDialog()
api.mock({ ...invitesApi.listReturns([anInvite()]), delayMs: 3000 })
const list = api.hold(invitesApi.listReturns([anInvite()]))

await users.createInviteAndSeeTheLinkBeforeTheList()
await users.createInviteAndSeeTheLinkBeforeTheList(list)

await expect(users.at.linkField).toBeVisible()
})
Expand Down Expand Up @@ -266,13 +268,13 @@ test.describe('the invites of a tenant admin', () => {
usersApi.roleChanges(demoted),
usersApi.oneIs(demoted),
membershipApi.userIsNow(demoted),
{ ...tenantsApi.oneIs(aTenant()), delayMs: 300 },
invitesApi.listFails(aProblem().forbidden('You cannot manage users.')),
)
const tenant = api.hold(tenantsApi.oneIs(aTenant()))
await people.confirmRole(id)
const invitesReads = api.all('get', invitesPaths.list).length

expect(await users.goToUsersAndCountTheButtonsBeforeTheTenantAnswers()).toBe(0)
expect(await users.goToUsersAndCountTheButtonsBeforeTheTenantAnswers(tenant)).toBe(0)

await expect(users.at.usersGrid).toBeVisible()
await expect(users.at.inviteButton).toHaveCount(0)
Expand Down
Loading
Loading