@srsholmes/tauri-playwright 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,483 @@
1
+ # tauri-playwright
2
+
3
+ Playwright E2E testing for Tauri desktop apps. Controls the real native webview (WKWebView, WebView2, WebKitGTK) with a Playwright-compatible API — auto-waiting, locator assertions, semantic selectors, network mocking, native screenshots, and video recording.
4
+
5
+ ## The Problem
6
+
7
+ Tauri apps use system webviews instead of Chromium. Playwright requires Chrome DevTools Protocol (CDP), but only WebView2 (Windows) supports it. **Standard Playwright integration is impossible on macOS and Linux.**
8
+
9
+ ## The Solution
10
+
11
+ Three testing modes from the same test files:
12
+
13
+ | Mode | Platform | How it works |
14
+ |---|---|---|
15
+ | `browser` | All | Headless Chromium with mocked Tauri IPC. Fast, CI-friendly. |
16
+ | `tauri` | All | Socket bridge to the real Tauri webview. True E2E. |
17
+ | `cdp` | Windows | Direct CDP to WebView2. Full native Playwright. |
18
+
19
+ ```
20
+ ┌──────────────────┐ socket/JSON ┌──────────────────────────────────┐
21
+ │ Playwright │◄────────────►│ tauri-plugin-playwright │
22
+ │ test runner │ │ (Rust, embedded in your app) │
23
+ │ │ │ │
24
+ │ @srsholmes/ │ │ Socket server → JS injection │
25
+ │ tauri-playwright │ │ HTTP polling ← JS results │
26
+ └──────────────────┘ └──────────────────────────────────┘
27
+ ```
28
+
29
+ ## Quick Start
30
+
31
+ ### 1. Add the Rust plugin to your Tauri app
32
+
33
+ ```toml
34
+ # src-tauri/Cargo.toml
35
+ [features]
36
+ e2e-testing = ["tauri-plugin-playwright"]
37
+
38
+ [dependencies]
39
+ tauri-plugin-playwright = { version = "0.1", optional = true }
40
+ ```
41
+
42
+ ```rust
43
+ // src-tauri/src/lib.rs
44
+ pub fn run() {
45
+ let mut builder = tauri::Builder::default()
46
+ .invoke_handler(tauri::generate_handler![/* your commands */]);
47
+
48
+ #[cfg(feature = "e2e-testing")]
49
+ {
50
+ builder = builder.plugin(tauri_plugin_playwright::init());
51
+ }
52
+
53
+ builder.run(tauri::generate_context!()).expect("error running app");
54
+ }
55
+ ```
56
+
57
+ ### 2. Install the npm package
58
+
59
+ ```bash
60
+ pnpm add -D @srsholmes/tauri-playwright @playwright/test
61
+ npx playwright install chromium
62
+ ```
63
+
64
+ ### 3. Create test fixtures
65
+
66
+ ```ts
67
+ // e2e/fixtures.ts
68
+ import { createTauriTest } from '@srsholmes/tauri-playwright';
69
+
70
+ export const { test, expect } = createTauriTest({
71
+ devUrl: 'http://localhost:1420',
72
+ ipcMocks: {
73
+ greet: (args) => `Hello, ${(args as { name?: string })?.name}!`,
74
+ },
75
+ mcpSocket: '/tmp/tauri-playwright.sock',
76
+ });
77
+ ```
78
+
79
+ ### 4. Write tests
80
+
81
+ ```ts
82
+ // e2e/tests/app.spec.ts
83
+ import { test, expect } from '../fixtures';
84
+
85
+ test('counter increments', async ({ tauriPage }) => {
86
+ await tauriPage.click('[data-testid="btn-increment"]');
87
+ await expect(tauriPage.locator('[data-testid="counter-value"]')).toContainText('1');
88
+ });
89
+
90
+ test('greets via Tauri IPC', async ({ tauriPage }) => {
91
+ await tauriPage.fill('[data-testid="greet-input"]', 'World');
92
+ await tauriPage.click('[data-testid="btn-greet"]');
93
+ await expect(tauriPage.getByTestId('greet-result')).toContainText('Hello, World!');
94
+ });
95
+ ```
96
+
97
+ ### 5. Configure Playwright
98
+
99
+ ```ts
100
+ // e2e/playwright.config.ts
101
+ import { defineConfig, devices } from '@playwright/test';
102
+
103
+ export default defineConfig({
104
+ testDir: './tests',
105
+ projects: [
106
+ {
107
+ name: 'browser-only',
108
+ use: { ...devices['Desktop Chrome'], mode: 'browser' },
109
+ },
110
+ {
111
+ name: 'tauri',
112
+ use: { mode: 'tauri' },
113
+ },
114
+ ],
115
+ webServer: {
116
+ command: 'pnpm dev',
117
+ port: 1420,
118
+ reuseExistingServer: !process.env.CI,
119
+ },
120
+ });
121
+ ```
122
+
123
+ ### 6. Run tests
124
+
125
+ ```bash
126
+ # Browser mode (headless, no Tauri needed)
127
+ npx playwright test --project=browser-only
128
+
129
+ # Tauri mode (start the app first)
130
+ cargo tauri dev --features e2e-testing # Terminal 1
131
+ npx playwright test --project=tauri # Terminal 2
132
+ ```
133
+
134
+ ## API Reference
135
+
136
+ ### Page Methods
137
+
138
+ All actions auto-wait for the element to be visible and enabled (default 5s timeout, configurable).
139
+
140
+ #### Interactions
141
+
142
+ ```ts
143
+ await tauriPage.click(selector, { timeout? })
144
+ await tauriPage.dblclick(selector)
145
+ await tauriPage.hover(selector)
146
+ await tauriPage.fill(selector, text)
147
+ await tauriPage.type(selector, text) // character by character
148
+ await tauriPage.press(selector, 'Enter')
149
+ await tauriPage.check(selector)
150
+ await tauriPage.uncheck(selector)
151
+ await tauriPage.selectOption(selector, value)
152
+ await tauriPage.focus(selector)
153
+ await tauriPage.blur(selector)
154
+ await tauriPage.dragAndDrop(source, target)
155
+ await tauriPage.dispatchEvent(selector, 'custom-event')
156
+ ```
157
+
158
+ #### Queries (auto-wait for element)
159
+
160
+ ```ts
161
+ const text = await tauriPage.textContent(selector)
162
+ const html = await tauriPage.innerHTML(selector)
163
+ const visible = await tauriPage.innerText(selector)
164
+ const value = await tauriPage.inputValue(selector)
165
+ const attr = await tauriPage.getAttribute(selector, name)
166
+ const box = await tauriPage.boundingBox(selector)
167
+ const css = await tauriPage.getComputedStyle(selector, 'color')
168
+ const all = await tauriPage.allTextContents(selector)
169
+ ```
170
+
171
+ #### State Checks (instant, no waiting)
172
+
173
+ ```ts
174
+ await tauriPage.isVisible(selector) // false if not found
175
+ await tauriPage.isHidden(selector)
176
+ await tauriPage.isChecked(selector)
177
+ await tauriPage.isDisabled(selector)
178
+ await tauriPage.isEnabled(selector)
179
+ await tauriPage.isEditable(selector)
180
+ await tauriPage.isFocused(selector)
181
+ await tauriPage.count(selector) // 0 if none found
182
+ ```
183
+
184
+ #### Navigation
185
+
186
+ ```ts
187
+ await tauriPage.goto(url)
188
+ await tauriPage.reload()
189
+ await tauriPage.goBack()
190
+ await tauriPage.goForward()
191
+ await tauriPage.waitForURL('/dashboard')
192
+ const title = await tauriPage.title()
193
+ const url = await tauriPage.url()
194
+ const html = await tauriPage.content()
195
+ ```
196
+
197
+ #### Waiting
198
+
199
+ ```ts
200
+ await tauriPage.waitForSelector(selector, timeout?)
201
+ await tauriPage.waitForFunction('document.readyState === "complete"', timeout?)
202
+ await tauriPage.waitForURL('/dashboard', { timeout: 10000 })
203
+ ```
204
+
205
+ #### Evaluate
206
+
207
+ ```ts
208
+ const result = await tauriPage.evaluate<number>('window.innerWidth')
209
+ ```
210
+
211
+ ### Semantic Selectors
212
+
213
+ ```ts
214
+ tauriPage.getByTestId('submit')
215
+ tauriPage.getByText('Hello World')
216
+ tauriPage.getByRole('button', { name: 'Submit' })
217
+ tauriPage.getByLabel('Email')
218
+ tauriPage.getByPlaceholder('Enter name')
219
+ tauriPage.getByAltText('Logo')
220
+ tauriPage.getByTitle('Close')
221
+ ```
222
+
223
+ ### Locator API
224
+
225
+ ```ts
226
+ const locator = tauriPage.locator('[data-testid="list"]')
227
+
228
+ // Actions
229
+ await locator.click()
230
+ await locator.fill('text')
231
+ await locator.press('Enter')
232
+ await locator.clear()
233
+ await locator.pressSequentially('hello', { delay: 50 })
234
+ await locator.dispatchEvent('input')
235
+
236
+ // Queries
237
+ await locator.textContent()
238
+ await locator.innerText()
239
+ await locator.inputValue()
240
+ await locator.getAttribute('href')
241
+ await locator.evaluate('(el) => el.dataset.custom')
242
+
243
+ // State
244
+ await locator.isVisible()
245
+ await locator.isChecked()
246
+ await locator.isFocused()
247
+
248
+ // Refinement
249
+ locator.nth(2)
250
+ locator.first()
251
+ locator.last()
252
+ locator.filter({ hasText: 'Active' })
253
+ await locator.all() // returns array of locators
254
+
255
+ // Nesting
256
+ locator.locator('.child')
257
+ locator.getByTestId('item')
258
+ locator.getByText('Click me')
259
+
260
+ // Scrolling
261
+ await locator.scrollIntoViewIfNeeded()
262
+ ```
263
+
264
+ ### Assertions
265
+
266
+ Custom `expect` matchers with auto-retry (default 5s timeout):
267
+
268
+ ```ts
269
+ // Visibility
270
+ await expect(locator).toBeVisible()
271
+ await expect(locator).toBeHidden()
272
+ await expect(locator).not.toBeVisible()
273
+
274
+ // Content
275
+ await expect(locator).toContainText('Hello')
276
+ await expect(locator).toContainText(/hello/i) // regex
277
+ await expect(locator).toHaveText('Hello World') // exact match
278
+
279
+ // Form state
280
+ await expect(locator).toHaveValue('test')
281
+ await expect(locator).toBeChecked()
282
+ await expect(locator).toBeEnabled()
283
+ await expect(locator).toBeDisabled()
284
+ await expect(locator).toBeEditable()
285
+ await expect(locator).toBeFocused()
286
+ await expect(locator).toBeEmpty()
287
+
288
+ // Attributes
289
+ await expect(locator).toHaveAttribute('type', 'text')
290
+ await expect(locator).toHaveClass('active')
291
+ await expect(locator).toHaveCSS('color', 'rgb(255, 0, 0)')
292
+ await expect(locator).toHaveId('main')
293
+
294
+ // Collections
295
+ await expect(locator).toHaveCount(5)
296
+ await expect(locator).toBeAttached()
297
+
298
+ // Page-level
299
+ await expect(tauriPage).toHaveURL('/dashboard')
300
+ await expect(tauriPage).toHaveTitle('My App')
301
+ ```
302
+
303
+ ### Keyboard & Mouse
304
+
305
+ ```ts
306
+ // Keyboard
307
+ await tauriPage.keyboard.press('Enter')
308
+ await tauriPage.keyboard.press('Control+A')
309
+ await tauriPage.keyboard.type('hello world', { delay: 50 })
310
+ await tauriPage.keyboard.down('Shift')
311
+ await tauriPage.keyboard.up('Shift')
312
+
313
+ // Mouse
314
+ await tauriPage.mouse.click(100, 200)
315
+ await tauriPage.mouse.click(100, 200, { button: 'right' })
316
+ await tauriPage.mouse.dblclick(100, 200)
317
+ await tauriPage.mouse.move(300, 400)
318
+ await tauriPage.mouse.wheel(0, 100)
319
+ ```
320
+
321
+ ### Network Mocking
322
+
323
+ ```ts
324
+ // Mock an API endpoint
325
+ await tauriPage.route('/api/users', {
326
+ status: 200,
327
+ body: JSON.stringify({ users: ['Alice', 'Bob'] }),
328
+ contentType: 'application/json',
329
+ });
330
+
331
+ // Click a button that fetches from the mocked endpoint
332
+ await tauriPage.click('[data-testid="fetch-btn"]');
333
+ await expect(tauriPage.getByTestId('user-0')).toContainText('Alice');
334
+
335
+ // Verify network requests were captured
336
+ const requests = await tauriPage.getNetworkRequests();
337
+ expect(requests.find(r => r.url.includes('/api/users'))).toBeTruthy();
338
+
339
+ // Clean up
340
+ await tauriPage.unroute('/api/users');
341
+ await tauriPage.clearRoutes();
342
+ ```
343
+
344
+ ### Dialog Handling
345
+
346
+ ```ts
347
+ await tauriPage.installDialogHandler({
348
+ defaultConfirm: true,
349
+ defaultPromptText: 'Claude',
350
+ });
351
+
352
+ await tauriPage.click('[data-testid="btn-confirm"]');
353
+
354
+ const dialogs = await tauriPage.getDialogs();
355
+ expect(dialogs[0].type).toBe('confirm');
356
+ expect(dialogs[0].message).toBe('Are you sure?');
357
+ ```
358
+
359
+ ### File Upload
360
+
361
+ ```ts
362
+ await tauriPage.setInputFiles('[data-testid="file-input"]', [
363
+ { name: 'test.txt', mimeType: 'text/plain', buffer: Buffer.from('hello') },
364
+ ]);
365
+ ```
366
+
367
+ ### Screenshots & Video
368
+
369
+ ```ts
370
+ // Native screenshot (CoreGraphics on macOS — captures real window with title bar)
371
+ const png = await tauriPage.screenshot();
372
+ await tauriPage.screenshot({ path: '/tmp/screenshot.png' });
373
+
374
+ // Video recording (native frame capture → ffmpeg → MP4)
375
+ await tauriPage.startRecording({ path: '/tmp/recording', fps: 15 });
376
+ // ... run test actions ...
377
+ const result = await tauriPage.stopRecording();
378
+ console.log(result.video); // '/tmp/recording/video.mp4'
379
+ ```
380
+
381
+ The fixture automatically records video and captures screenshots on failure, attaching them to the Playwright HTML report.
382
+
383
+ ### IPC Mocking (Browser Mode)
384
+
385
+ Mock any Tauri `invoke()` command, including plugin commands:
386
+
387
+ ```ts
388
+ createTauriTest({
389
+ devUrl: 'http://localhost:1420',
390
+ ipcMocks: {
391
+ greet: (args) => `Hello, ${args?.name}!`,
392
+ get_config: () => ({ theme: 'dark', lang: 'en' }),
393
+ 'plugin:fs|read': () => 'file contents',
394
+ 'plugin:dialog|open': () => '/path/to/file',
395
+ },
396
+ });
397
+ ```
398
+
399
+ Assert which IPC commands were called:
400
+
401
+ ```ts
402
+ import { getCapturedInvokes, clearCapturedInvokes } from '@srsholmes/tauri-playwright';
403
+
404
+ const calls = await getCapturedInvokes(tauriPage);
405
+ expect(calls).toContainEqual(
406
+ expect.objectContaining({ cmd: 'greet', args: { name: 'World' } })
407
+ );
408
+ ```
409
+
410
+ ## Plugin Configuration
411
+
412
+ ```rust
413
+ use tauri_plugin_playwright::PluginConfig;
414
+
415
+ // Default: Unix socket at /tmp/tauri-playwright.sock
416
+ builder = builder.plugin(tauri_plugin_playwright::init());
417
+
418
+ // Custom socket path + TCP fallback
419
+ builder = builder.plugin(tauri_plugin_playwright::init_with_config(
420
+ PluginConfig::new()
421
+ .socket_path("/tmp/my-app-pw.sock")
422
+ .tcp_port(6274)
423
+ ));
424
+ ```
425
+
426
+ ## CDP Mode (Windows)
427
+
428
+ On Windows, WebView2 supports Chrome DevTools Protocol for full native Playwright:
429
+
430
+ ```bash
431
+ # Launch with CDP enabled
432
+ WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS="--remote-debugging-port=9222" cargo tauri dev
433
+ ```
434
+
435
+ ```ts
436
+ // Playwright config
437
+ {
438
+ name: 'cdp',
439
+ use: { mode: 'cdp' },
440
+ }
441
+
442
+ // Fixture config
443
+ createTauriTest({
444
+ cdpEndpoint: 'http://localhost:9222',
445
+ // ...
446
+ });
447
+ ```
448
+
449
+ ## Example App
450
+
451
+ See [`examples/hello-world/`](examples/hello-world/) for a complete working example with:
452
+
453
+ - React frontend with counter, greet (Tauri IPC), todo list, modal, file upload, dialogs, drag & drop, API fetch
454
+ - Rust backend with greet command + playwright plugin
455
+ - **67 E2E tests** across 10 spec files covering every API method
456
+ - **127 unit tests** for the TypeScript library
457
+ - Playwright config with browser-only and Tauri projects
458
+
459
+ ## Requirements
460
+
461
+ - **Tauri 2.0** with `"withGlobalTauri": true` in `tauri.conf.json`
462
+ - **Node.js 18+**
463
+ - **Rust toolchain** (for Tauri mode)
464
+ - **ffmpeg** (optional, for video stitching)
465
+ - **Screen recording permission** on macOS (for native screenshots)
466
+
467
+ ## CI/CD
468
+
469
+ GitHub Actions workflow included (`.github/workflows/e2e.yml`):
470
+
471
+ ```yaml
472
+ # Browser-only tests run on ubuntu (fast, headless)
473
+ npx playwright test --project=browser-only
474
+
475
+ # Tauri tests run on macOS (real app, native screenshots)
476
+ npx playwright test --project=tauri
477
+ ```
478
+
479
+ Test results, HTML reports, and videos are uploaded as artifacts.
480
+
481
+ ## License
482
+
483
+ MIT