browser_tester 1.5.0

Deterministic lightweight browser runtime for Rust tests
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# browser-tester Mock Guide

## Overview

`browser-tester` treats test mocks as first-class runtime features.
The goal is to let tests control browser-like behavior deterministically without relying on a real browser environment.

This document groups the main mock families and shows representative usage.

## Mock Maintenance Rule

When adding a new test-only mock capability, keep the mock public surface and its documentation in sync.

Required checklist:

- add or update the public API
- add a minimal usage example
- add tests, including failure-path coverage when relevant
- document any call capture or artifact capture behavior
- update `README.md`
- update this file

## Common Pattern

Most mock-backed tests follow the same shape:

1. Build a `Harness`
2. Seed deterministic mock state
3. Trigger a user-like action
4. Assert DOM state or inspect captured artifacts

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = "<button id='run'>run</button>";
    let mut h = Harness::from_html(html)?;
    h.click("#run")?;
    Ok(())
}
```

## Fetch

Main APIs:

- `set_fetch_mock(url, body)`
- `set_fetch_mock_response(url, status, body)`
- `clear_fetch_mocks()`
- `take_fetch_calls()`

Example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        document.getElementById('run').addEventListener('click', () => {
          fetch('https://app.local/api/message')
            .then((res) => res.text())
            .then((text) => {
              document.getElementById('out').textContent = text;
            });
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.set_fetch_mock("https://app.local/api/message", "hello");
    h.click("#run")?;
    h.assert_text("#out", "hello")?;
    assert_eq!(
        h.take_fetch_calls(),
        vec!["https://app.local/api/message".to_string()]
    );
    Ok(())
}
```

Use `set_fetch_mock_response` when status code matters:

```rust
h.set_fetch_mock_response("https://app.local/api/message", 404, "missing");
```

## Dialogs and Print

Main APIs:

- `enqueue_confirm_response(bool)`
- `set_default_confirm_response(bool)`
- `enqueue_prompt_response(Option<&str>)`
- `set_default_prompt_response(Option<&str>)`
- `take_alert_messages()`
- `take_print_call_count()`

Example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        document.getElementById('run').addEventListener('click', () => {
          const accepted = confirm('continue?');
          const answer = prompt('name?');
          document.getElementById('out').textContent =
            `${accepted}:${answer ?? 'null'}`;
          alert('done');
          window.print();
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.enqueue_confirm_response(true);
    h.enqueue_prompt_response(Some("Alice"));
    h.click("#run")?;
    h.assert_text("#out", "true:Alice")?;
    assert_eq!(h.take_alert_messages(), vec!["done".to_string()]);
    assert_eq!(h.take_print_call_count(), 1);
    Ok(())
}
```

## Location and History-Backed Mock Pages

Main APIs:

- `set_location_mock_page(url, html)`
- `clear_location_mock_pages()`
- `take_location_navigations()`
- `location_reload_count()`

Example:

```rust
use browser_tester::{Harness, LocationNavigation, LocationNavigationKind};

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='go'>go</button>
      <script>
        document.getElementById('go').addEventListener('click', () => {
          location.assign('https://app.local/next');
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.set_location_mock_page("https://app.local/next", "<p id='msg'>next page</p>");
    h.click("#go")?;
    h.assert_text("#msg", "next page")?;

    assert_eq!(
        h.take_location_navigations(),
        vec![LocationNavigation {
            kind: LocationNavigationKind::Assign,
            from: "about:blank".to_string(),
            to: "https://app.local/next".to_string(),
        }]
    );
    Ok(())
}
```

For `history.go(0)`, `history.back()`, or `history.forward()`, provide deterministic pages for the URLs that may be visited:

```rust
let mut h = Harness::from_html(html)?;
h.set_location_mock_page("about:blank", "<p id='marker'>reloaded</p>");
h.click("#run")?;
h.assert_text("#marker", "reloaded")?;
```

## Clipboard

Main APIs:

- `set_clipboard_text(text)`
- `clipboard_text()`
- `set_clipboard_read_error(Some(name))`
- `set_clipboard_write_error(Some(name))`
- `clear_clipboard_errors()`
- `take_clipboard_writes()`
- `copy(selector)`
- `paste(selector)`
- script-side override via `navigator.clipboard = { ... }`

Read example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        document.getElementById('run').addEventListener('click', () => {
          navigator.clipboard.readText().then((text) => {
            document.getElementById('out').textContent = text;
          });
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.set_clipboard_text("seeded");
    h.click("#run")?;
    h.assert_text("#out", "seeded")?;
    Ok(())
}
```

Binary write capture example:

```rust
use browser_tester::{ClipboardPayloadArtifact, ClipboardWriteArtifact, Harness};

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <script>
        document.getElementById('run').addEventListener('click', async () => {
          const pngBlob = new Blob([new Uint8Array([137, 80, 78, 71, 1, 2, 3])], {
            type: 'image/png'
          });
          await navigator.clipboard.write([
            new ClipboardItem({ 'image/png': pngBlob })
          ]);
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.click("#run")?;
    assert_eq!(
        h.take_clipboard_writes(),
        vec![ClipboardWriteArtifact {
            payloads: vec![ClipboardPayloadArtifact {
                mime_type: "image/png".to_string(),
                bytes: vec![137, 80, 78, 71, 1, 2, 3],
            }],
        }]
    );
    Ok(())
}
```

Script-side override example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        navigator.clipboard = {
          readText: () => Promise.resolve('stubbed-read'),
          writeText: () => Promise.resolve('stubbed-write'),
        };
        document.getElementById('run').addEventListener('click', () => {
          navigator.clipboard.writeText('x')
            .then(() => navigator.clipboard.readText())
            .then((text) => {
              document.getElementById('out').textContent = text;
            });
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.click("#run")?;
    h.assert_text("#out", "stubbed-read")?;
    Ok(())
}
```

## localStorage Seed State

Main APIs:

- `Harness::from_html_with_local_storage(...)`
- `Harness::from_html_with_url_and_local_storage(...)`

Example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <p id='out'></p>
      <script>
        document.getElementById('out').textContent =
          localStorage.getItem('token') || 'missing';
      </script>
    "#;

    let h = Harness::from_html_with_local_storage(html, &[("token", "seeded-token")])?;
    h.assert_text("#out", "seeded-token")?;
    Ok(())
}
```

`window.localStorage` is also assignable inside script when a local stub is more convenient than Rust-side seeding.

## Download Capture

Main APIs:

- `take_downloads()`

Download capture works for deterministic flows such as `Blob` + `URL.createObjectURL()` + `<a download>.click()`.

Example:

```rust
use browser_tester::{DownloadArtifact, Harness};

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <script>
        document.getElementById('run').addEventListener('click', () => {
          const blob = new Blob(['a,b\n1,2\n'], { type: 'text/csv;charset=utf-8;' });
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = 'report.csv';
          a.click();
          URL.revokeObjectURL(url);
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.click("#run")?;
    assert_eq!(
        h.take_downloads(),
        vec![DownloadArtifact {
            filename: Some("report.csv".to_string()),
            mime_type: Some("text/csv;charset=utf-8;".to_string()),
            bytes: b"a,b\n1,2\n".to_vec(),
        }]
    );
    Ok(())
}
```

## File Inputs

Main APIs:

- `set_input_files(selector, &[MockFile { ... }, ...])`
- `MockFile::new(name)`

Behavior:

- when selection changes: dispatch `input` then `change`
- when selection does not change: dispatch `cancel`
- for non-`multiple` inputs, only the first mock file is selected
- mocked files expose `arrayBuffer()` / `text()` / `bytes()` / `stream()`
- mocked image files can be consumed by `createImageBitmap(file)`

Example:

```rust
use browser_tester::{Harness, MockFile};

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <input id='upload' type='file' multiple required>
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        const input = document.getElementById('upload');
        document.getElementById('run').addEventListener('click', () => {
          const files = input.files;
          document.getElementById('out').textContent =
            input.value + ':' + files.length + ':' + files.map((f) => f.name).join(',');
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.set_input_files(
        "#upload",
        &[
            MockFile::new("first.txt").with_text("hello"),
            MockFile {
                name: "nested/second.txt".to_string(),
                size: 7,
                mime_type: "text/plain".to_string(),
                last_modified: 99,
                webkit_relative_path: "nested/second.txt".to_string(),
                bytes: b"second!".to_vec(),
            },
        ],
    )?;
    h.click("#run")?;
    h.assert_text("#out", "C:\\fakepath\\first.txt:2:first.txt,second.txt")?;
    Ok(())
}
```

## matchMedia

Main APIs:

- `set_match_media_mock(query, matches)`
- `set_default_match_media_matches(matches)`
- `clear_match_media_mocks()`
- `take_match_media_calls()`

Example:

```rust
use browser_tester::Harness;

fn main() -> browser_tester::Result<()> {
    let html = r#"
      <button id='run'>run</button>
      <p id='out'></p>
      <script>
        document.getElementById('run').addEventListener('click', () => {
          const result = window.matchMedia('(prefers-reduced-motion: reduce)');
          document.getElementById('out').textContent = String(result.matches);
        });
      </script>
    "#;

    let mut h = Harness::from_html(html)?;
    h.set_match_media_mock("(prefers-reduced-motion: reduce)", true);
    h.click("#run")?;
    h.assert_text("#out", "true")?;
    assert_eq!(
        h.take_match_media_calls(),
        vec!["(prefers-reduced-motion: reduce)".to_string()]
    );
    Ok(())
}
```

## Related Documents

- Architecture overview: [architecture.md]architecture.md
- Public package README: [../README.md]../README.md