Community编程与开发github.com

playwright-blazor-testing

使用 Playwright 为 Blazor 应用程序(Server 或 WebAssembly)编写 UI 测试。涵盖导航、交互、身份验证、选择器和常见的 Blazor 特定模式。

playwright-blazor-testing 是什么?

该技能为 Blazor 应用程序(包括 Blazor Server 和 WebAssembly 模式)提供端到端的 UI 测试解决方案,使用 Playwright 框架。它涵盖了编写稳定测试所需的核心概念,例如等待 Blazor 的异步渲染、使用 `data-test` 属性作为可靠的选择器,以及处理 Blazor 特有的错误 UI(如 `#blazor-error-ui`)。技能详细介绍了多种测试模式,包括页面导航(区分初始加载和客户端内部路由)、表单填写、点击与触摸交互、身份验证(通过交互式登录、Cookie 注入或 OAuth 模拟)以及实时更新(SignalR)的验证。此外,它还提供了屏幕截图和视觉回归测试的方法,以及针对 HTTPS 开发证书和 CI/CD(如 GitHub Actions)集成的配置建议。该技能特别强调了 Blazor Server 测试中的并行化策略,以避免 SignalR 连接饱和。

兼容平台~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="*" />
  <!-- 或使用 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("浏览器未初始化");

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

        _browser = await _playwright.Chromium.LaunchAsync(new()
        {
            Headless = true,
            // 对于 CI/调试,您可能需要:
            // Headless = Environment.GetEnvironmentVariable("CI") != null,
            // SlowMo = 100 // 减慢操作速度以进行调试
        });
    }

    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();

    // 首次加载是经典的 HTTP 导航
    await page.GotoAsync("https://localhost:5001");

    // 等待 Blazor 初始化
    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");

    // 方法 1:点击导航链接
    await page.GetByRole(AriaRole.Link, new() { Name = "Counter" })
        .ClickAsync();

    // 等待新的页面内容(而不是网络空闲!)
    await page.WaitForSelectorAsync("h1:has-text('Counter')");

    // 方法 2:程序化导航(Blazor 8+)
    await page.EvaluateAsync("window.Blazor.navigateTo('/fetchdata')");
    await page.WaitForSelectorAsync("h1:has-text('Weather')");

    // 方法 3:直接 URL 导航(会导致完全重新加载)
    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">
    提交
</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);

    // 使用 GetByTestId 获取带有 data-test 属性的元素
    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");

    // 填写登录表单
    await page.FillAsync("input[name='username']", "alice");
    await page.FillAsync("input[name='password']", "P@ssw0rd");
    await page.ClickAsync("button[type='submit']");

    // 等待重定向到仪表板
    await page.WaitForURLAsync("**/dashboard");

    // 验证已登录
    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();

    // 注入身份验证 cookie
    await page.Context.AddCookiesAsync(new[]
    {
        new Cookie
        {
            Name = ".AspNetCore.Cookies",
            Value = GenerateAuthCookie("alice"),
            Url = baseUrl,
            Secure = true,
            HttpOnly = true
        }
    });

    // 直接导航到受保护的页面
    await page.GotoAsync($"{baseUrl}/dashboard");

    // 已通过身份验证!
    var username = await page.TextContentAsync("[data-test='user-name']");
    Assert.Equal("alice", username);
}

private string GenerateAuthCookie(string username)
{
    // 生成有效的身份验证 cookie
    // 这需要访问您的应用程序的 cookie 加密密钥
    // 或者使用生成有效 cookie 的测试端点
    // 或者实际执行一次登录并重用该 cookie
}

OAuth/外部提供程序模拟

// 使用路由拦截来模拟 OAuth 重定向
await page.RouteAsync("**/signin-microsoft", async route =>
{
    // 拦截 OAuth 重定向并返回模拟响应
    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);

    // 标准点击
    await page.GetByText("点击我").ClickAsync();

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

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

    // 悬停然后点击下拉菜单
    var menu = page.Locator("#profile-menu");
    await menu.HoverAsync();
    await menu.GetByText("退出").ClickAsync();

    // 触摸事件(移动端模拟)
    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");

    // 文本输入
    await page.FillAsync("[data-test='name']", "John Doe");

    // 选择下拉菜单
    await page.SelectOptionAsync("[data-test='country']", "US");

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

    // 单选按钮
    await page.CheckAsync("[data-test='option-a']");

    // 文件上传
    await page.SetInputFilesAsync("[data-test='file-input']",
        "/path/to/test-file.pdf");

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

    // 等待成功消息
    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 错误:{errorText}");
    }
}

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

    // 执行一些操作
    await page.ClickAsync("[data-test='action-button']");

    // 验证没有错误发生
    await page.AssertNoBlazorErrors();
}

模式 8:测试实时更新(SignalR)

Blazor Server 使用 SignalR 进行实时通信:

[Fact]
public async Task RealTimeUpdates()
{
    // 打开两个浏览器上下文(模拟两个用户)
    var page1 = await _fixture.Browser.NewPageAsync();
    var page2 = await _fixture.Browser.NewPageAsync();

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

    // 用户 1 画了一些东西
    await page1.ClickAsync("[data-test='draw-button']");
    await page1.Mouse.ClickAsync(100, 100);

    // 用户 2 应该看到更新
    await page2.WaitForSelectorAsync("[data-test='drawing-canvas']");

    // 验证两个页面显示相同的内容
    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);

    // 全页屏幕截图
    await page.ScreenshotAsync(new()
    {
        Path = "screenshots/homepage.png",
        FullPage = true
    });

    // 元素屏幕截图
    var header = page.Locator("header");
    await header.ScreenshotAsync(new()
    {
        Path = "screenshots/header.png"
    });

    // 带视口大小的屏幕截图
    await page.SetViewportSizeAsync(1920, 1080);
    await page.ScreenshotAsync(new()
    {
        Path = "screenshots/desktop.png"
    });

    // 移动端视口
    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,
        // 忽略本地开发证书的证书错误
        Args = new[] { "--ignore-certificate-errors" }
    });
}

对于更严格的设置,导出并信任开发证书:

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

Blazor 组件的常用选择器

// 按角色(最适合无障碍性)
await page.GetByRole(AriaRole.Button, new() { Name = "提交" });
await page.GetByRole(AriaRole.Link, new() { Name = "首页" });
await page.GetByRole(AriaRole.Heading, new() { Name = "欢迎" });

// 按测试 ID
await page.GetByTestId("user-profile");

// 按文本内容
await page.GetByText("你好,世界!");

// 按标签(用于输入框)
await page.GetByLabel("电子邮件地址");

// 按占位符
await page.GetByPlaceholder("输入您的姓名");

// CSS 选择器(谨慎使用)
await page.Locator(".mud-button-primary");
await page.Locator("#login-form");

// XPath(作为最后手段使用)
await page.Locator("xpath=//button[contains(text(), '提交')]");

并行化注意事项

Blazor Server 使用 SignalR WebSocket。多个 Playwright 测试可能会使连接饱和:

// 限制 Blazor Server 测试的并行执行
[Collection("Blazor Server")]
public class BlazorServerTests { }

// 在 AssemblyInfo.cs 或测试启动时
[assembly: CollectionBehavior(MaxParallelThreads = 2)]

Blazor WebAssembly 没有此限制,可以完全并行运行。

CI/CD 集成

GitHub Actions

name: Playwright 测试

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

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

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

    - name: 安装 Playwright 浏览器
      run: pwsh -Command "playwright install --with-deps"

    - name: 构建
      run: dotnet build -c Release

    - name: 运行 Playwright 测试
      run: |
        dotnet test tests/YourApp.UITests \
          --no-build \
          -c Release \
          --logger trx

    - name: 上传屏幕截图
      uses: actions/upload-artifact@v3
      if: failure()
      with:
        name: playwright-screenshots
        path: "**/screenshots/"

    - name: 上传测试结果
      uses: actions/upload-artifact@v3

Azure DevOps

trigger:
- main

pool:
  vmImage: 'ubuntu-latest'

variables:
  buildConfiguration: 'Release'

steps:
- task: UseDotNet@2
  displayName: '安装 .NET SDK'
  inputs:
    packageType: 'sdk'
    version: '9.0.x'

- task: PowerShell@2
  displayName: '安装 Playwright 浏览器'
  inputs:
    targetType: 'inline'
    script: 'pwsh -Command "playwright install --with-deps"'

- task: DotNetCoreCLI@2
  displayName: '运行 Playwright 测试'
  inputs:
    command: 'test'
    projects: 'tests/YourApp.UITests/*.csproj'
    arguments: '--configuration $(buildConfiguration) --logger trx'

- task: PublishTestResults@2
  displayName: '发布测试结果'
  condition: succeededOrFailed()
  inputs:
    testRunner: 'VSTest'
    testResultsFiles: '**/*.trx'

调试技巧

  1. 有头模式运行:设置 Headless = false 以观察浏览器行为
  2. 使用 SlowMo:设置 SlowMo = 500 以减慢所有操作
  3. 记录控制台输出:page.Console += (_, msg) => Console.WriteLine(msg.Text);
  4. 记录页面错误:page.PageError += (_, error) => Console.WriteLine(error);
  5. 使用 Playwright 代码生成器:
    playwright codegen https://localhost:5001
    
  6. 捕获跟踪以进行调试:
    await page.Context.Tracing.StartAsync(new()
    {
        Screenshots = true,
        Snapshots = true
    });
    // ... 测试代码 ...
    await page.Context.Tracing.StopAsync(new()
    {
        Path = "trace.zip"
    });
    

常见 Blazor 模式

EditForm 验证

[Fact]
public async Task EditFormValidation()
{
    await page.GotoAsync($"{baseUrl}/register");

    // 提交空表单以触发验证
    await page.ClickAsync("[data-test='register-submit']");

    // 等待验证消息
    await page.WaitForSelectorAsync("[data-test='validation-summary']");

    var errors = page.Locator(".validation-message");
    await Assert.That(errors.CountAsync() > 0);
}

数据网格/表格交互

[Fact]
public async Task DataGridPagination()
{
    await page.GotoAsync($"{baseUrl}/grid");

    // 点击下一页按钮
    await page.ClickAsync("[data-test='next-page']");

    // 等待新数据加载
    await page.WaitForSelectorAsync("[data-test='row-11']");

    // 获取行数
    var rows = page.Locator("[data-test^='row-']");
    Assert.Equal(10, await rows.CountAsync());
}

模态对话

[Fact]
public async Task ModalDialogInteraction()
{
    await page.GotoAsync($"{baseUrl}/modal");

    // 打开模态框
    await page.ClickAsync("[data-test='open-modal']");

    // 等待模态框可见
    await page.WaitForSelectorAsync("[data-test='modal']");

    // 在模态框内交互
    await page.FillAsync("[data-test='modal-input']", "测试输入");
    await page.ClickAsync("[data-test='modal-save']");

    // 等待模态框关闭
    await page.WaitForSelectorAsync("[data-test='modal']",
        new() { State = WaitForSelectorState.Hidden });
}

故障排除

问题解决方案
测试间歇性失败增加超时时间 page.SetDefaultTimeoutAsync(30_000)
#blazor-error-ui 可见检查未处理的异常;验证组件生命周期
元素未找到确保 Blazor 已完成渲染;使用更长的等待
Cookie 身份验证失败检查 cookie 名称、路径和加密密钥
SignalR 断开连接验证 WebSocket 连接;增加连接限制
屏幕截图不匹配固定浏览器版本;禁用动画

包摘要

使用 Playwright 有效测试 Blazor 应用程序需要理解 Blazor 的异步渲染模型和客户端路由。关键要点:

  • 使用测试属性进行稳定的元素选择
  • 等待 DOM 元素而不是网络事件
  • 处理 Blazor 特定的错误 UI
  • 使用适当的身份验证策略
  • 模拟真实用户交互
  • 在 CI 中并行运行,并在 Blazor Server 中注意连接限制

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.

相关技能