Testing WebAssembly in the Browser with Playwright

Testing WebAssembly in the Browser with Playwright

WebAssembly unit tests with wasm-pack cover your Rust or C logic. What they don't cover is whether your Wasm module works correctly when embedded in a real web page — async initialization, JavaScript interop, error handling, UI integration, and cross-browser compatibility. That's what Playwright is for.

This guide covers practical Playwright patterns for testing WebAssembly browser applications: detecting initialization, calling Wasm functions through the UI, handling async patterns, testing across browsers, and setting up CI.

The Challenge with Wasm in Browser Tests

WebAssembly has characteristics that make browser testing tricky:

  1. Async initialization — WebAssembly.instantiate() is async; the module isn't ready immediately after page load
  2. No DOM presence — Wasm computation happens invisibly; you need to trigger it through UI and observe results
  3. Memory ownership — Wasm manages its own memory; JavaScript errors from Wasm can be cryptic
  4. Browser variation — Wasm feature support varies (SIMD, threads, exceptions) across browsers
  5. Large binary downloads — .wasm files can be megabytes; slow CI networks cause timeout failures

Detecting Wasm Initialization

The most common Playwright mistake with Wasm apps is interacting before the module is ready. Wasm initialization is async — the page may render before Wasm is callable.

Pattern 1: Signal via a DOM element

In your app code:

async function initApp() {
  await init(); // wasm-pack generated init()
  document.body.setAttribute('data-wasm-ready', 'true');
}
initApp();

In Playwright:

// Wait for the data attribute before any interactions
await page.waitForSelector('[data-wasm-ready="true"]');

Pattern 2: Signal via a global variable

async function initApp() {
  await init();
  window.wasmReady = true;
}
await page.waitForFunction(() => window.wasmReady === true, {
  timeout: 10000  // Wasm downloads can be slow in CI
});

Pattern 3: Wait for UI element that only appears after init

async function initApp() {
  await init();
  document.getElementById('app-loading').hidden = true;
  document.getElementById('app-content').hidden = false;
}
await page.waitForSelector('#app-content:not([hidden])');

Pick one pattern and stick with it. The DOM attribute approach is most debuggable — you can see it in the Elements panel.

Testing Wasm Computation Through the UI

Most Wasm functionality is triggered by user actions and shows results in the DOM. Test these as you would any other user flow:

import { test, expect } from '@playwright/test';

test.describe('WebAssembly image processor', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/image-processor');
    await page.waitForSelector('[data-wasm-ready="true"]');
  });

  test('grayscale conversion changes image appearance', async ({ page }) => {
    // Upload a test image
    const fileInput = page.locator('[data-testid="image-upload"]');
    await fileInput.setInputFiles('test-fixtures/sample-image.jpg');

    // Wait for preview to appear
    await expect(page.locator('[data-testid="image-preview"]')).toBeVisible();

    // Apply grayscale (triggers Wasm processing)
    await page.click('[data-testid="apply-grayscale"]');

    // Wait for processing indicator to disappear
    await expect(page.locator('[data-testid="processing-spinner"]')).toBeHidden();

    // Take screenshot for visual regression
    await expect(page.locator('[data-testid="image-preview"]'))
      .toHaveScreenshot('grayscale-result.png', { maxDiffPixels: 50 });
  });

  test('processing time is displayed', async ({ page }) => {
    await page.setInputFiles('[data-testid="image-upload"]', 'test-fixtures/sample-image.jpg');
    await page.click('[data-testid="apply-grayscale"]');
    await expect(page.locator('[data-testid="processing-spinner"]')).toBeHidden();

    const timeText = await page.locator('[data-testid="processing-time"]').textContent();
    expect(timeText).toMatch(/\d+(\.\d+)? ms/);
  });

  test('shows error for unsupported file type', async ({ page }) => {
    await page.setInputFiles('[data-testid="image-upload"]', 'test-fixtures/document.pdf');
    await expect(page.locator('[data-testid="error-message"]')).toContainText('Unsupported file type');
  });
});

Testing Wasm Execution Directly via page.evaluate

For tests that need to call Wasm functions directly (bypassing the UI), use page.evaluate():

test('Wasm fibonacci function returns correct values', async ({ page }) => {
  await page.goto('/');
  await page.waitForFunction(() => window.wasmReady === true);

  // Call the Wasm function directly
  const results = await page.evaluate(() => {
    return [
      window.wasm.fibonacci(0),
      window.wasm.fibonacci(1),
      window.wasm.fibonacci(10),
      window.wasm.fibonacci(20),
    ];
  });

  expect(results).toEqual([0, 1, 55, 6765]);
});

test('Wasm handles edge cases without crashing', async ({ page }) => {
  await page.goto('/');
  await page.waitForFunction(() => window.wasmReady === true);

  // Test that errors are handled gracefully
  const consoleErrors: string[] = [];
  page.on('console', msg => {
    if (msg.type() === 'error') consoleErrors.push(msg.text());
  });

  await page.evaluate(() => {
    try {
      window.wasm.process_data(null);
    } catch (e) {
      // Expected to throw
    }
  });

  // Should not produce unhandled Wasm trap errors
  const wasmErrors = consoleErrors.filter(e => e.includes('RuntimeError') || e.includes('unreachable'));
  expect(wasmErrors).toHaveLength(0);
});

Testing Wasm Workers (Multi-threading)

Wasm can run in Web Workers for CPU-intensive work without blocking the main thread:

test('image processing runs in a worker without blocking UI', async ({ page }) => {
  await page.goto('/heavy-processor');
  await page.waitForSelector('[data-wasm-ready="true"]');

  // Upload a large image
  await page.setInputFiles('[data-testid="image-input"]', 'test-fixtures/4k-image.jpg');

  // Click process (which starts a worker)
  await page.click('[data-testid="process-btn"]');

  // UI should remain interactive while processing
  const uiButton = page.locator('[data-testid="cancel-btn"]');
  await expect(uiButton).toBeEnabled();

  // Wait for processing to complete
  await expect(page.locator('[data-testid="result-canvas"]')).toBeVisible({
    timeout: 30000
  });

  // Verify the button changed state
  await expect(page.locator('[data-testid="process-btn"]')).toHaveText('Process Again');
});

Cross-Browser Testing for Wasm Features

Wasm feature support varies. SIMD, threads, and exception handling are not universally available:

// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
    {
      name: 'mobile-chrome',
      use: { ...devices['Pixel 7'] },
    },
  ],
});

Test that your app handles missing Wasm features gracefully:

test('falls back to JavaScript when Wasm SIMD is not supported', async ({ page, browserName }) => {
  if (browserName === 'chromium') {
    // Disable SIMD in Chromium to test fallback
    // This requires launching with specific flags
    test.skip(true, 'SIMD testing requires custom browser args');
  }

  await page.goto('/');
  await page.waitForSelector('[data-wasm-ready="true"]');

  // Verify the app works (possibly slower, but correctly)
  await page.fill('[data-testid="input"]', '100');
  await page.click('[data-testid="compute"]');
  await expect(page.locator('[data-testid="result"]')).not.toBeEmpty();
});

Performance Testing in Playwright

Measure Wasm execution time from the browser's perspective:

test('image processing completes within performance budget', async ({ page }) => {
  await page.goto('/image-processor');
  await page.waitForSelector('[data-wasm-ready="true"]');

  await page.setInputFiles('[data-testid="image-input"]', 'test-fixtures/1mp-image.jpg');

  // Measure the processing time
  const startTime = await page.evaluate(() => performance.now());

  await page.click('[data-testid="process-btn"]');
  await expect(page.locator('[data-testid="processing-spinner"]')).toBeHidden({ timeout: 10000 });

  const endTime = await page.evaluate(() => performance.now());
  const elapsed = endTime - startTime;

  console.log(`Processing time: ${elapsed.toFixed(0)}ms`);

  // 1MP image should process in under 2 seconds
  expect(elapsed).toBeLessThan(2000);
});

test('Wasm startup time is acceptable', async ({ page }) => {
  const navigationStart = Date.now();
  
  await page.goto('/');
  await page.waitForSelector('[data-wasm-ready="true"]');
  
  const initTime = Date.now() - navigationStart;
  console.log(`Wasm init time: ${initTime}ms`);
  
  // Wasm should be ready within 5 seconds of navigation
  expect(initTime).toBeLessThan(5000);
});

Testing Wasm Error States

Wasm errors (traps) cause JavaScript exceptions. Test that your app handles them correctly:

test('handles Wasm out-of-memory gracefully', async ({ page }) => {
  await page.goto('/large-data-processor');
  await page.waitForSelector('[data-wasm-ready="true"]');

  // Intercept console errors
  const errors: string[] = [];
  page.on('console', msg => {
    if (msg.type() === 'error') errors.push(msg.text());
  });

  // Listen for unhandled promise rejections
  const rejections: string[] = [];
  page.on('pageerror', err => rejections.push(err.message));

  // Try to process data that might exceed memory
  await page.fill('[data-testid="size-input"]', '1000000000'); // 1GB
  await page.click('[data-testid="process-btn"]');

  // Should show user-friendly error, not crash
  await expect(page.locator('[data-testid="error-message"]')).toBeVisible();
  await expect(page.locator('[data-testid="error-message"]')).toContainText(/too large|memory/i);

  // Should not have unhandled errors
  expect(rejections.filter(r => r.includes('RuntimeError'))).toHaveLength(0);
});

CI Configuration for Wasm Playwright Tests

name: Wasm Browser Tests
on: [push, pull_request]

jobs:
  wasm-playwright:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      
      - uses: actions/setup-node@v4
        with:
          node-version: 20

      - name: Install Rust + wasm-pack
        run: |
          curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

      - name: Build Wasm
        run: wasm-pack build --target web --release

      - name: Install npm deps
        run: npm ci

      - name: Install Playwright
        run: npx playwright install --with-deps

      - name: Build web app
        run: npm run build

      - name: Start test server
        run: npx serve dist -l 3000 &

      - name: Wait for server
        run: npx wait-on http://localhost:3000

      - name: Run Playwright tests
        run: npx playwright test
        env:
          # Increase timeout for Wasm download in CI
          PLAYWRIGHT_TIMEOUT: 30000

      - name: Upload artifacts on failure
        if: failure()
        uses: actions/upload-artifact@v4
        with:
          name: playwright-report
          path: playwright-report/

Caching Wasm Builds in CI

Building Wasm is slow (Rust compilation). Cache aggressively:

- name: Cache Rust dependencies
  uses: actions/cache@v4
  with:
    path: |
      ~/.cargo/registry
      ~/.cargo/git
      target/
    key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }}

- name: Cache wasm-pack output
  uses: actions/cache@v4
  with:
    path: pkg/
    key: ${{ runner.os }}-wasm-${{ hashFiles('src/**/*.rs', 'Cargo.lock') }}

Monitoring Wasm Apps in Production

Wasm modules can fail in production for reasons that never appear in tests: network issues preventing .wasm download, browser extensions interfering with WebAssembly, CDN serving stale builds, or feature detection failures on unusual browser versions.

HelpMeTest runs browser-level tests against your live application on a schedule. It navigates to your pages, waits for Wasm initialization, exercises your features, and alerts you when anything breaks. Same Playwright test patterns, running continuously against production.

Summary

Playwright testing for WebAssembly apps requires a few patterns that differ from regular web apps:

  1. Always wait for Wasm initialization — use a DOM signal or global flag, never arbitrary timeouts
  2. Test through the UI and via page.evaluate() — cover both user flows and Wasm function contracts
  3. Test error states explicitly — Wasm traps become JS exceptions; verify they're handled gracefully
  4. Run cross-browser — Wasm feature support varies; Safari and Firefox have different capabilities than Chrome
  5. Set generous timeouts for Wasm download — CI networks are slow; .wasm files are large

Wasm adds one extra initialization step to your Playwright setup. Once past that, tests look identical to any other browser application.

Read more

Start now free