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
8 changes: 8 additions & 0 deletions docs/api-mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,14 @@ it("should call the API exactly twice", async () => {
});
```

::: tip The count can lag one hit behind the UI
The service worker reports each hit with a message, and that message can reach the page after the mocked response it belongs to has already rendered. When you assert a count right after the UI changed, check it inside `twd.waitFor`:

```ts
await twd.waitFor(() => expect(twd.getRequestCount("getUser")).to.equal(2));
```
:::

### `getRequestCounts()`

Returns a snapshot of all mock rule hit counts as an object.
Expand Down
2 changes: 2 additions & 0 deletions docs/api/assertions.md
Original file line number Diff line number Diff line change
Expand Up @@ -557,6 +557,8 @@ visibleDiv.should("not.be.hidden");

## URL Assertions

`twd.url().should()` retries until the assertion passes: by default 30 attempts 100ms apart, so up to 3000ms, the same as `findBy*`. Pass `retries` to change it.

### eq (URL)

Verifies that the current URL matches exactly.
Expand Down
20 changes: 17 additions & 3 deletions docs/api/twd-commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ twd.url(): URLCommandAPI

#### Methods

- `should(assertion, value, retries?)` - Make URL assertions (async, retries with 100ms delay between attempts, default: 5 retries)
- `should(assertion, value, retries?)` - Make URL assertions (async, retries with 100ms delay between attempts, default: 30 retries, so up to 3000ms)

#### Examples

Expand Down Expand Up @@ -822,8 +822,22 @@ twd.waitForRequest(alias: string, retries?: number, retryDelay?: number): Promis
#### Parameters

- **alias** (`string`) - The alias of the mock to wait for
- **retries** (`number`, optional) - Maximum number of retry attempts (default: `10`)
- **retryDelay** (`number`, optional) - Delay between retries in milliseconds (default: `100`)
- **retries** (`number`, optional) - Together with `retryDelay`, sets the timeout: `retries * retryDelay` ms (default: `30`, so 3000ms, the same as `findBy*`)
- **retryDelay** (`number`, optional) - See `retries` (default: `100`)

#### What it waits for

It resolves as soon as the service worker reports the request, plus two animation frames for the mocked response to reach the app. It guarantees the request **happened**, not that the UI has updated: if your app processes the response asynchronously (a data-fetching library, derived state), the screen can change a moment later. Wait for the UI with `findBy*` or `twd.waitFor`:

```ts
await twd.waitForRequest("filtered");

// ❌ May run before the filtered list has rendered
expect(screenDom.queryAllByText("old.csv").length).to.equal(0);

// ✅ Retries until the UI reflects the response
await twd.waitFor(() => expect(screenDom.queryAllByText("old.csv").length).to.equal(0));
```

#### Returns

Expand Down
7 changes: 4 additions & 3 deletions docs/component-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,10 @@ afterEach(() => {
});
```

Use `afterEach`, not `beforeEach`. TWD runs after-hooks in a `finally`, so this
still runs when a test fails, and it puts the app back before your flow tests need
it. If you also mock requests, `twd.clearRequestMockRules()` belongs in
Use `afterEach`, not `beforeEach`. TWD runs after-hooks even when a test fails,
so this always puts the app back before your flow tests need it. If an `afterEach`
itself throws, that test fails (and is retried like any failure) and the run goes
on. If you also mock requests, `twd.clearRequestMockRules()` belongs in
`beforeEach` as usual.

That is the whole setup.
Expand Down
14 changes: 14 additions & 0 deletions docs/testing-library.md
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,20 @@ const email = screenDom.getByLabelText("Email:");
const modal = screenDomGlobal.getByRole("dialog", { name: "Confirm" });
```

#### Put the expected state in the query

`findBy*` returns as soon as a matching element exists, and that includes an element that was already on screen before your action. When an action changes the state of an element that is already there (a pagination button becoming current, a tab becoming selected), query for the new state, so the lookup waits for it:

```ts
await userEvent.click(await screenDom.findByRole("button", { name: "2" }));

// ❌ Finds the "2" button that was already there, before the page changed
const page = await screenDom.findByRole("button", { name: "2" });

// ✅ Waits until "2" is the current page
const page = await screenDom.findByRole("button", { name: "2", current: "page" });
```

### When `twd.get()` is the right call

Only when no Testing Library query reaches the element: a third-party widget that renders bare `<div>`s or a `<canvas>`, or markup you don't own and can't add a role, label or `data-testid` to. If you are reaching for `twd.get()` on your own components, that usually means they are missing an accessible name, which is worth fixing in the component.
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/api-mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ The new command here is:
await twd.waitForRequest("getTodoList");
```

It waits until the mocked request is triggered — useful when you need to ensure data is rendered before asserting UI state.
It waits until the mocked request is triggered (up to 3 seconds by default). That tells you the request happened, not that the UI has updated, so assert on the result with `findBy*`.

> Always define `mockRequest` before triggering the request (clicks, submits, or navigation).
> If you mock it too late, it might not intercept properly.
Expand Down
9 changes: 9 additions & 0 deletions specs/2026-10-18-wait-for-request-polling-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,12 @@ A faster `twd.visit()` (two frames instead of 100ms) was tried in the same
round and dropped: in `twd-test-app` it made a test click a button from the
screen that was about to be replaced, in 4 out of 5 runs. `visit` keeps its
fixed 100ms.

## Follow-up: 3000ms defaults, like findBy*

Running a 550-test app on a CPU-throttled machine showed two defaults were too
short for a 2-vCPU CI runner: `waitForRequest` (1000ms) and
`twd.url().should()` (500ms), while `findBy*` already waits up to 3000ms. Both
now default to 3000ms (30 attempts 100ms apart). Tests that pass are not
slower; a failing one takes longer to be reported. Explicit `retries` and
`retryDelay` are respected as before.
13 changes: 7 additions & 6 deletions src/commands/mockBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,21 +310,22 @@ const waitForHit = async (alias: string, retries: number, retryDelay: number): P

/**
* Wait for a mocked request to be made.
* Resolves once the service worker reports the hit and the app has had time to
* receive and render the mocked response.
* Resolves once the service worker reports the hit, plus two frames for the
* response to reach the app. It guarantees the request happened, not that the
* UI has updated: wait for that with findBy* or `twd.waitFor`.
* @param alias The alias of the mock rule to wait for
* @param retries Together with `retryDelay`, sets the timeout: `retries * retryDelay` ms
* @param retries Together with `retryDelay`, sets the timeout: `retries * retryDelay` ms (3000ms by default, like findBy*)
* @param retryDelay Together with `retries`, sets the timeout: `retries * retryDelay` ms
* @returns The matched rule (with body if applicable)
*/
export const waitForRequest = async (
alias: string,
retries = 10,
retries = 30,
retryDelay = 100,
): Promise<Rule> => {
const rule = await waitForHit(alias, retries, retryDelay);
// The worker reports the hit before it returns the response, so let the
// response arrive and render before the test goes on
// The worker reports the hit before it returns the response, so give the
// response a moment to reach the app before the test goes on
await settle();
return rule;
};
Expand Down
2 changes: 1 addition & 1 deletion src/commands/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const should = (name: AnyURLAssertion, value: string) => {
const urlCommand = (): URLCommandAPI => {
return {
location: window.location,
should: async (name: AnyURLAssertion, value: string, retries = 5) => {
should: async (name: AnyURLAssertion, value: string, retries = 30) => {
let error: Error | undefined;
for (let i = 0; i < retries; i++) {
try {
Expand Down
21 changes: 15 additions & 6 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,21 +370,30 @@ export class TestRunner {
let lastError: Error | null = null;

for (let attempt = 1; attempt <= this.retryCount; attempt++) {
let attemptError: Error | null = null;
try {
for (const hook of hooks.before) await hook();
test.logs = [];
test.diagnostics = undefined;
await test.handler();
this.events.onPass(test, attempt > 1 ? attempt : undefined);
return;
} catch (err) {
lastError = err as Error;
// Inside `catch`, never after `finally`: an `afterEach` calling
// clearRequestMockRules() resets the counts this reads.
attemptError = err as Error;
// Before the afterEach hooks: one calling clearRequestMockRules()
// resets the counts this reads.
test.diagnostics = collectDiagnostics();
} finally {
}
// A throwing afterEach fails this test instead of escaping and ending the
// whole run. The test's own error, when there is one, is the one reported.
try {
for (const hook of hooks.after) await hook();
} catch (err) {
attemptError ??= err as Error;
}
if (!attemptError) {
this.events.onPass(test, attempt > 1 ? attempt : undefined);
return;
}
lastError = attemptError;
}

this.events.onFail(test, lastError!);
Expand Down
20 changes: 20 additions & 0 deletions src/tests/commands/mockBridge/waitForRequestEvents.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,26 @@ describe('waitForRequest driven by EXECUTED messages', () => {
await assertion;
});

it('waits 3000ms by default, like findBy*', async () => {
await mockRequest('users', { method: 'GET', url: '/users', response: [] });
vi.useFakeTimers();
let settled = false;
const pending = waitForRequest('users');
pending
.catch(() => {})
.finally(() => {
settled = true;
});

await vi.advanceTimersByTimeAsync(2999);
expect(settled).toBe(false);
const assertion = expect(pending).rejects.toThrow(
'Rule "users" was not executed within 3000ms.',
);
await vi.advanceTimersByTimeAsync(1);
await assertion;
});

it('drops pending waits on clearRequestMockRules so they never settle into the next test', async () => {
await mockRequest('users', { method: 'GET', url: '/users', response: [] });
vi.useFakeTimers();
Expand Down
8 changes: 6 additions & 2 deletions src/tests/commands/mockBridge/waitForRequests.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,15 +55,19 @@ describe('waitForRequests', () => {
const secondAlias = 'secondAlias';
await mockRequest(alias, { method: 'GET', url: '/bar', response: {} });
await mockRequest(secondAlias, { method: 'POST', url: '/foo', response: {} });
vi.useFakeTimers();
setTimeout(() => {
const rules = getRequestMockRules();
rules[0].executed = true;
rules[0].request = { delayed: true };
// Simulate waiter callback (directly resolve the promise by marking executed)
// The waitFor promise will resolve on next tick after executed is set
}, 50);
await expect(waitForRequests([alias, secondAlias])).rejects.toThrow(
`Rule "${secondAlias}" was not executed within 1000ms.`,
const assertion = expect(waitForRequests([alias, secondAlias])).rejects.toThrow(
`Rule "${secondAlias}" was not executed within 3000ms.`,
);
await vi.advanceTimersByTimeAsync(3000);
await assertion;
vi.useRealTimers();
});
});
40 changes: 38 additions & 2 deletions src/tests/e2e/url.spec.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi, afterAll } from 'vitest';
import { beforeEach, describe, expect, it, vi, afterAll, afterEach } from 'vitest';
import { twd } from '../..';

describe('twd url command', () => {
Expand All @@ -25,6 +25,10 @@ describe('twd url command', () => {
};
});

afterEach(() => {
vi.useRealTimers();
});

afterAll(() => {
// Restore original location after all tests
// @ts-expect-error -- restoring window.location that was deleted in beforeEach
Expand Down Expand Up @@ -64,7 +68,7 @@ describe('twd url command', () => {

it('should fail equality assertion with incorrect URL', async () => {
const urlCmd = twd.url();
await expect(urlCmd.should('eq', 'http://localhost:3000/about')).rejects.toThrow(
await expect(urlCmd.should('eq', 'http://localhost:3000/about', 1)).rejects.toThrow(
'Assertion failed: Expected URL to be http://localhost:3000/about, but got http://localhost:3000/home',
);
});
Expand Down Expand Up @@ -94,6 +98,38 @@ describe('twd url command', () => {
expect(result).toContain('Assertion passed');
});

it('should keep retrying for 3000ms by default, like findBy*', async () => {
vi.useFakeTimers();
const urlCmd = twd.url();
// The app navigates 2s after the action, which is slow but normal on a busy CI runner
setTimeout(() => {
window.location.href = 'http://localhost:3000/about';
}, 2000);
const pending = urlCmd.should('eq', 'http://localhost:3000/about');
await vi.advanceTimersByTimeAsync(2100);
await expect(pending).resolves.toContain('Assertion passed');
vi.useRealTimers();
});

it('should give up after 3000ms by default', async () => {
vi.useFakeTimers();
let settled = false;
const pending = twd.url().should('eq', 'http://localhost:3000/never');
pending
.catch(() => {})
.finally(() => {
settled = true;
});
await vi.advanceTimersByTimeAsync(2899);
expect(settled).toBe(false);
const assertion = expect(pending).rejects.toThrow(
'Expected URL to be http://localhost:3000/never',
);
await vi.advanceTimersByTimeAsync(200);
await assertion;
vi.useRealTimers();
});

it('should throw the last failure when no retry passes', async () => {
const urlCmd = twd.url();
await expect(urlCmd.should('contain.url', '/about', 2)).rejects.toThrow(
Expand Down
88 changes: 88 additions & 0 deletions src/tests/runner/twd-runner.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,3 +482,91 @@ describe('twd runner', () => {
});
});
});

describe('twd runner hook failures', () => {
const events = () => ({
onStart: vi.fn(),
onPass: vi.fn(),
onFail: vi.fn(),
onSkip: vi.fn(),
});

beforeEach(() => {
twd.clearTests();
vi.clearAllMocks();
});

it('fails the test and keeps running the next ones when an afterEach throws', async () => {
const nextTest = vi.fn();
twd.describe('Suite with a broken afterEach', () => {
twd.afterEach(() => {
throw new Error('afterEach broke');
});
twd.it('first test', () => {});
});
twd.describe('Next suite', () => {
twd.it('next test', nextTest);
});

const mockEvents = events();
const runner = new twd.TestRunner(mockEvents);
await expect(runner.runAll()).resolves.toBeDefined();

expect(mockEvents.onFail).toHaveBeenCalledWith(
expect.objectContaining({ name: 'first test' }),
expect.objectContaining({ message: 'afterEach broke' }),
);
expect(nextTest).toHaveBeenCalledTimes(1);
});

it('does not report a test as passed when its afterEach throws', async () => {
twd.describe('Suite with a broken afterEach', () => {
twd.afterEach(() => {
throw new Error('afterEach broke');
});
twd.it('passing test', () => {});
});

const mockEvents = events();
await new twd.TestRunner(mockEvents).runAll();

expect(mockEvents.onPass).not.toHaveBeenCalled();
expect(mockEvents.onFail).toHaveBeenCalledTimes(1);
});

it('keeps the test error when both the test and its afterEach throw', async () => {
twd.describe('Suite with a broken afterEach', () => {
twd.afterEach(() => {
throw new Error('afterEach broke');
});
twd.it('failing test', () => {
throw new Error('test broke');
});
});

const mockEvents = events();
await new twd.TestRunner(mockEvents).runAll();

expect(mockEvents.onFail).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({ message: 'test broke' }),
);
});

it('retries a test whose afterEach failed on the first attempt', async () => {
let afterCalls = 0;
twd.describe('Suite with a flaky afterEach', () => {
twd.afterEach(() => {
afterCalls++;
if (afterCalls === 1) throw new Error('afterEach broke');
});
twd.it('test', () => {});
});

const mockEvents = events();
await new twd.TestRunner(mockEvents, { retryCount: 2 }).runAll();

expect(mockEvents.onPass).toHaveBeenCalledTimes(1);
expect(mockEvents.onFail).not.toHaveBeenCalled();
});
});
Loading