Community程式設計與開發github.com

playwright-blazor-testing

使用 Playwright 為 Blazor 應用程式(Server 或 WebAssembly)撰寫 UI 測試。涵蓋導航、互動、驗證、選擇器及常見的 Blazor 專屬模式。

playwright-blazor-testing 是什麼?

此技能說明如何使用 Playwright 端對端 UI 測試框架來測試 Blazor 應用程式,無論是 Blazor Server 還是 Blazor WebAssembly。其核心原則強調正確的等待策略,因為 Blazor 的異步渲染特性;使用穩定的 `data-test` 屬性選擇器,而非易變的 CSS 類別;並建議在 CI/CD 環境中採用無頭模式,在本地除錯時使用有頭模式。技能提供了詳細的程式碼範例,涵蓋初始頁面載入、應用程式內部導航(無頁面重新載入)、表單填寫、檔案上傳、點擊與觸控互動,以及處理 Blazor 專屬問題,例如 SignalR 即時更新和 `#blazor-error-ui` 錯誤 overlay。此外,還包含驗證流程(如互動式登入、Cookie 注入和 OAuth 模擬)、螢幕截圖擷取、HTTPS 開發憑證處理,以及 GitHub Actions 與 GitLab CI 的 CI/CD 整合範例。技能支援以 .NET 和 Playwright 為基礎的測試,並提供了 MS Test 和 xUnit 兩種測試框架的 NuGet 套件參考。對於 Blazor Server 測試,特別建議限制並行執行以避免 SignalR 連線飽和,而 Blazor WebAssembly 則無此限制。

相容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/playwright-blazor

Installed? Explore more 程式設計與開發 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

使用 Playwright 測試 Blazor 應用程式

何時使用此技能

請在以下情況使用此技能:

  • 為 Blazor Server 或 WebAssembly 應用程式撰寫端對端 UI 測試
  • 測試互動式元件、表單和使用者工作流程
  • 驗證身份驗證和授權流程
  • 測試 Blazor Server 中基於 SignalR 的即時更新
  • 為視覺回歸測試擷取螢幕截圖
  • 測試響應式設計和行動裝置模擬
  • 使用瀏覽器開發者工具除錯 UI 問題

核心原則

  1. 等待渲染 - Blazor 非同步渲染;使用適當的等待策略
  2. 測試屬性 - 使用 data-test 或 data-testid 屬性作為穩定的選擇器
  3. 預設無頭模式 - 在 CI 中以無頭模式執行測試,在本地除錯時使用有頭模式
  4. 處理錯誤 UI - 始終檢查 #blazor-error-ui 以捕捉未處理的例外
  5. 避免網路等待狀態 - Blazor 導航不會觸發網路載入;等待 DOM 變更
  6. 固定瀏覽器通道 - 為確保可重複性,使用特定的瀏覽器通道(msedge, chrome)

必要的 NuGet 套件

<ItemGroup>
  <PackageReference Include="Microsoft.Playwright" Version="*" />
  <PackageReference Include="Microsoft.Playwright.MSTest" Version="*" />
  <!-- OR for xUnit -->
  <PackageReference Include="xunit" Version="*" />
  <PackageReference Include="xunit.runner.visualstudio" Version="*" />
</ItemGroup>

安裝

在執行測試之前,請安裝 Playwright 瀏覽器:

pwsh -Command "playwright install --with-deps"

模式 1:基本 Playwright 設定

using Microsoft.Playwright;

public class PlaywrightFixture : IAsyncLifetime
{
    private IPlaywright? _playwright;
    private IBrowser? _browser;

    public IBrowser Browser => _browser
        ?? throw new InvalidOperationException("Browser not initialized");

    public async Task InitializeAsync()
    {
        _playwright = await Playwright.CreateAsync();

        _browser = await _playwright.Chromium.LaunchAsync(new()
        {
            Headless = true,
            // For CI/debugging, you might want:
            // Headless = Environment.GetEnvironmentVariable("CI") != null,
            // SlowMo = 100 // Slow down actions for debugging
        });
    }

    public async Task DisposeAsync()
    {
        if (_browser is not null)
            await _browser.DisposeAsync();

        _playwright?.Dispose();
    }
}

模式 2:在 Blazor 應用程式中導航

初始頁面載入(傳統導航)

[Fact]
public async Task InitialPageLoad()
{
    var page = await _fixture.Browser.NewPageAsync();

    // First load is classic HTTP navigation
    await page.GotoAsync("https://localhost:5001");

    // Wait for Blazor to initialize
    await page.WaitForSelectorAsync("h1:has-text('Welcome')");

    Assert.True(await page.IsVisibleAsync("h1:has-text('Welcome')"));
}

應用程式內部導航(無頁面重新載入)

Blazor 使用用戶端路由,因此後續導航不會觸發頁面重新載入:

[Fact]
public async Task InternalNavigation()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync("https://localhost:5001");

    // Method 1: Click a navigation link
    await page.GetByRole(AriaRole.Link, new() { Name = "Counter" })
        .ClickAsync();

    // Wait for the new page content (NOT network idle!)
    await page.WaitForSelectorAsync("h1:has-text('Counter')");

    // Method 2: Programmatic navigation (Blazor 8+)
    await page.EvaluateAsync("window.Blazor.navigateTo('/fetchdata')");
    await page.WaitForSelectorAsync("h1:has-text('Weather')");

    // Method 3: Direct URL navigation (causes full reload)
    await page.GotoAsync("https://localhost:5001/counter");
    await page.WaitForSelectorAsync("h1:has-text('Counter')");
}

Blazor 的等待策略

// ❌ 不可:等待網路空閒(Blazor 不會重新載入頁面)
await page.WaitForLoadStateAsync(LoadState.NetworkIdle);

// ✅ 可以:等待特定的 DOM 元素
await page.WaitForSelectorAsync("h1:has-text('My Page')");

// ✅ 可以:等待元素可見
await page.Locator("[data-test='content']").WaitForAsync();

// ✅ 可以:等待 URL 變更
await page.WaitForURLAsync("**/counter");

模式 3:使用測試屬性的穩定選擇器

在你的 Blazor 元件中

<!-- 為穩定的選擇器添加 data-test 屬性 -->
<button data-test="submit-button" @onclick="HandleSubmit">
    Submit
</button>

<input data-test="username-input" @bind="Username" />

<div data-test="result-container">
    @Result
</div>

在你的測試中

[Fact]
public async Task FormSubmission()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync(baseUrl);

    // 對具有 data-test 屬性的元素使用 GetByTestId
    await page.GetByTestId("username-input").FillAsync("testuser");
    await page.GetByTestId("password-input").FillAsync("password123");
    await page.GetByTestId("submit-button").ClickAsync();

    // 驗證結果
    var result = await page.GetByTestId("result-container").TextContentAsync();
    Assert.Contains("Success", result);
}

模式 4:處理身份驗證

互動式登入

[Fact]
public async Task LoginFlow()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync($"{baseUrl}/login");

    // Fill login form
    await page.FillAsync("input[name='username']", "alice");
    await page.FillAsync("input[name='password']", "P@ssw0rd");
    await page.ClickAsync("button[type='submit']");

    // Wait for redirect to dashboard
    await page.WaitForURLAsync("**/dashboard");

    // Verify logged in
    var username = await page.TextContentAsync("[data-test='user-name']");
    Assert.Equal("alice", username);
}

Cookie 注入(更快)

[Fact]
public async Task AuthenticatedAccess_ViaCookie()
{
    var page = await _fixture.Browser.NewPageAsync();

    // Inject authentication cookie
    await page.Context.AddCookiesAsync(new[]
    {
        new Cookie
        {
            Name = ".AspNetCore.Cookies",
            Value = GenerateAuthCookie("alice"),
            Url = baseUrl,
            Secure = true,
            HttpOnly = true
        }
    });

    // Navigate directly to protected page
    await page.GotoAsync($"{baseUrl}/dashboard");

    // Already authenticated!
    var username = await page.TextContentAsync("[data-test='user-name']");
    Assert.Equal("alice", username);
}

private string GenerateAuthCookie(string username)
{
    // Generate a valid authentication cookie
    // This requires access to your app's cookie encryption keys
    // OR use a test endpoint that generates valid cookies
    // OR perform actual login once and reuse the cookie
}

OAuth/外部提供者模擬

// 使用路由攔截來模擬 OAuth 重定向
await page.RouteAsync("**/signin-microsoft", async route =>
{
    // Intercept OAuth redirect and return mock response
    await route.FulfillAsync(new()
    {
        Status = 302,
        Headers = new Dictionary<string, string>
        {
            ["Location"] = $"{baseUrl}/signin-callback?code=mock_auth_code"
        }
    });
});

模式 5:點擊事件與觸控互動

[Fact]
public async Task ClickInteractions()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync(baseUrl);

    // Standard click
    await page.GetByText("Click Me").ClickAsync();

    // Right-click
    await page.ClickAsync("[data-test='context-menu']", new()
    {
        Button = MouseButton.Right
    });

    // Double-click
    await page.DblClickAsync("[data-test='item']");

    // Hover then click dropdown
    var menu = page.Locator("#profile-menu");
    await menu.HoverAsync();
    await menu.GetByText("Sign out").ClickAsync();

    // Touch events (mobile emulation)
    await page.EmulateMediaAsync(new() { Media = Media.Screen });
    await page.Touchscreen.TapAsync(150, 300);
}

模式 6:表單處理

[Fact]
public async Task ComplexForm()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync($"{baseUrl}/form");

    // Text input
    await page.FillAsync("[data-test='name']", "John Doe");

    // Select dropdown
    await page.SelectOptionAsync("[data-test='country']", "US");

    // Checkbox
    await page.CheckAsync("[data-test='terms']");

    // Radio button
    await page.CheckAsync("[data-test='option-a']");

    // File upload
    await page.SetInputFilesAsync("[data-test='file-input']",
        "/path/to/test-file.pdf");

    // Submit
    await page.ClickAsync("[data-test='submit']");

    // Wait for success message
    await page.WaitForSelectorAsync("[data-test='success-message']");
}

模式 7:處理 Blazor 錯誤 UI

當發生未處理的例外時,Blazor 會顯示一個錯誤覆蓋層。請始終檢查:

public static async Task AssertNoBlazorErrors(this IPage page)
{
    var errorUi = page.Locator("#blazor-error-ui");

    if (await errorUi.IsVisibleAsync())
    {
        var errorText = await errorUi.InnerTextAsync();
        Assert.Fail($"Blazor error occurred: {errorText}");
    }
}

[Fact]
public async Task Page_ShouldNotHaveErrors()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync(baseUrl);

    // Perform some actions
    await page.ClickAsync("[data-test='action-button']");

    // Verify no errors occurred
    await page.AssertNoBlazorErrors();
}

模式 8:測試即時更新(SignalR)

Blazor Server 使用 SignalR 進行即時通訊:

[Fact]
public async Task RealTimeUpdates()
{
    // Open two browser contexts (simulating two users)
    var page1 = await _fixture.Browser.NewPageAsync();
    var page2 = await _fixture.Browser.NewPageAsync();

    await page1.GotoAsync($"{baseUrl}/drawing");
    await page2.GotoAsync($"{baseUrl}/drawing");

    // User 1 draws something
    await page1.ClickAsync("[data-test='draw-button']");
    await page1.Mouse.ClickAsync(100, 100);

    // User 2 should see the update
    await page2.WaitForSelectorAsync("[data-test='drawing-canvas']");

    // Verify both pages show the same content
    var canvas1 = await page1.GetByTestId("drawing-canvas")
        .GetAttributeAsync("data-strokes");
    var canvas2 = await page2.GetByTestId("drawing-canvas")
        .GetAttributeAsync("data-strokes");

    Assert.Equal(canvas1, canvas2);
}

模式 9:螢幕截圖與視覺測試

[Fact]
public async Task CaptureScreenshots()
{
    var page = await _fixture.Browser.NewPageAsync();
    await page.GotoAsync(baseUrl);

    // Full page screenshot
    await page.ScreenshotAsync(new()
    {
        Path = "screenshots/homepage.png",
        FullPage = true
    });

    // Element screenshot
    var header = page.Locator("header");
    await header.ScreenshotAsync(new()
    {
        Path = "screenshots/header.png"
    });

    // Screenshot with viewport size
    await page.SetViewportSizeAsync(1920, 1080);
    await page.ScreenshotAsync(new()
    {
        Path = "screenshots/desktop.png"
    });

    // Mobile viewport
    await page.SetViewportSizeAsync(375, 667);
    await page.ScreenshotAsync(new()
    {
        Path = "screenshots/mobile.png"
    });
}

模式 10:針對 HTTPS 並使用開發憑證執行

public async Task InitializeAsync()
{
    _playwright = await Playwright.CreateAsync();

    _browser = await _playwright.Chromium.LaunchAsync(new()
    {
        Headless = true,
        // Ignore certificate errors for local dev certs
        Args = new[] { "--ignore-certificate-errors" }
    });
}

對於更嚴格的設定,請匯出並信任開發憑證:

dotnet dev-certs https --export-path cert.pfx -p YourPassword

Blazor 元件的常見選擇器

// 按角色(最適合無障礙性)
await page.GetByRole(AriaRole.Button, new() { Name = "Submit" });
await page.GetByRole(AriaRole.Link, new() { Name = "Home" });
await page.GetByRole(AriaRole.Heading, new() { Name = "Welcome" });

// 按測試 ID
await page.GetByTestId("user-profile");

// 按文字內容
await page.GetByText("Hello, World!");

// 按標籤(用於輸入)
await page.GetByLabel("Email Address");

// 按預留位置文字
await page.GetByPlaceholder("Enter your name");

// CSS 選擇器(謹慎使用)
await page.Locator(".mud-button-primary");
await page.Locator("#login-form");

// XPath(最後的手段)
await page.Locator("xpath=//button[contains(text(), 'Submit')]");

並行處理考量

Blazor Server 使用 SignalR websockets。多個 Playwright 測試可能會使連線飽和:

// 限制 Blazor Server 測試的並行執行
[Collection("Blazor Server")]
public class BlazorServerTests { }

// 在 AssemblyInfo.cs 或測試啟動設定中
[assembly: CollectionBehavior(MaxParallelThreads = 2)]

Blazor WebAssembly 沒有此限制,可以完全並行執行。

CI/CD 整合

GitHub Actions

name: Playwright Tests

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 9.0.x

    - name: Install Playwright Browsers
      run: pwsh -Command "playwright install --with-deps"

    - name: Build
      run: dotnet build -c Release

    - name: Run Playwright Tests
      run: |
        dotnet test tests/YourApp.UITests \
          --no-build \
          -c Release \
          --logger trx

    - name: Upload Screenshots
      uses: actions/upload-artifact@v3
      if: failure()
      with:
        name: playwright-screenshots
        path: "**/screenshots/"

    - name: Upload Test Results
      uses: actions/upload-artifact@v3
      if: always()
      with:
        name: test-results
        path: "**/TestResults/"

GitLab CI

stages:
  - test

playwright-tests:
  stage: test
  image: mcr.microsoft.com/dotnet/sdk:9.0
  before_script:
    - pwsh -Command "playwright install --with-deps"
  script:
    - dotnet build -c Release
    - dotnet test tests/YourApp.UITests --no-build -c Release
  artifacts:
    when: always
    paths:
      - "**/screenshots/"
      - "**/TestResults/"

故障排除

常見問題與解決方案

問題原因解決方案
元素未找到Blazor 尚未渲染使用 WaitForSelectorAsync,增加逾時時間
測試在 CI 中失敗缺少瀏覽器二進位檔確保使用 --with-deps 安裝瀏覽器
SignalR 連線失敗WebSocket 限制在測試中限制並行性
錯誤 UI 出現未處理的例外使用 AssertNoBlazorErrors 輔助方法
測試偶爾失敗競態條件新增明確等待,避免依賴網路空閒狀態

除錯技巧

// 啟用除錯日誌記錄
await using var trace = await page.TraceAsync();

// 使用 Browser Console 輸出
await page.EvaluateAsync("console.log('Debug info')");

// 在測試期間暫停
await page.PauseAsync();

// 對目前狀態截圖
await page.ScreenshotAsync(new() {
    Path = $"debug_{DateTime.Now.Ticks}.png"
});

結論

結合 Playwright 和 Blazor 提供了一個用於測試現代 Web 應用程式的強大組合。請記住:

  • 等待 Blazor 特定的 UI 變更,而非網路事件
  • 使用 data-test 屬性建立穩定的、不受重構影響的選擇器
  • 透過限制並行性來處理 Blazor Server 的 SignalR 限制
  • 始終檢查 Blazor 錯誤 UI 以確保應用程式穩定性
  • 使用螢幕截圖進行視覺回歸測試
  • 正確設定 CI/CD 以順暢執行測試

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相關技能