Community编程与开发github.com

verify-email-snapshots

使用 Verify 对电子邮件模板进行快照测试,以捕获回归问题。验证生成的 HTML 输出是否与批准的基线一致。适用于 MJML 模板和任何电子邮件渲染器。

verify-email-snapshots 是什么?

此技能指导开发者使用 Verify 测试库对电子邮件模板进行快照测试。它专门解决电子邮件模板的视觉复杂性和难以单元测试的问题,通过捕获渲染后的 HTML 并在发生意外更改时使测试失败,从而防止回归。该技能支持 MJML 模板和任何电子邮件渲染器,并提供了详细的安装、基本测试、审查更改、变量替换处理和测试夹具等实践指南。它还涵盖了动态值擦除、CI 集成和最佳实践,帮助开发团队在代码审查中轻松识别电子邮件渲染的更改。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/verify-email-snapshots

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

使用 Verify 对电子邮件模板进行快照测试

何时使用该技能

在以下情况下使用此技能:

  • 测试电子邮件模板渲染以防止回归
  • 验证 MJML 模板编译成预期的 HTML
  • 在代码审查中检查电子邮件更改(差异是可视化的)
  • 确保变量替换正常工作

相关技能:

  • aspnetcore/mjml-email-templates - MJML 模板编写
  • aspire/mailpit-integration - 本地测试电子邮件投递
  • testing/snapshot-testing - 通用 Verify 模式

为什么对电子邮件进行快照测试?

电子邮件模板:

  1. 可视化 - 小的更改可能会破坏跨客户端的渲染
  2. 难以进行单元测试 - 输出是复杂的 HTML,而不是简单的值
  3. 容易出现回归 - 模板更改可能产生意外效果

快照测试捕获渲染后的 HTML,并在其发生意外更改时失败。


安装

dotnet add package Verify.Xunit  # 或 Verify.NUnit, Verify.MSTest

基本的电子邮件快照测试

[Fact]
public async Task UserSignupInvitation_RendersCorrectly()
{
    // Arrange
    var renderer = _services.GetRequiredService<IMjmlTemplateRenderer>();

    var variables = new Dictionary<string, string>
    {
        { "PreviewText", "You've been invited to join Acme Corp" },
        { "OrganizationName", "Acme Corporation" },
        { "InviteeName", "John Doe" },
        { "InviterName", "Jane Admin" },
        { "InvitationLink", "https://example.com/invite/abc123" },
        { "ExpirationDate", "December 31, 2025" }
    };

    // Act
    var html = await renderer.RenderTemplateAsync(
        "UserInvitations/UserSignupInvitation",
        variables);

    // Assert
    await Verify(html, extension: "html");
}

这将在首次运行时创建 UserSignupInvitation_RendersCorrectly.verified.html。


审查电子邮件更改

当模板更改时,测试会失败并显示差异。审查选项:

1. 可视化差异工具

# 配置差异工具(一次性)
dotnet tool install -g verify.tool
verify accept  # 接受所有待处理的更改
verify review  # 打开差异工具

2. 浏览器预览

在浏览器中打开 .received.html 文件以查看实际渲染效果。

3. IDE 集成

大多数 IDE 会显示 .verified.html 与 .received.html 文件的内联差异。


测试每个模板变体

为每个电子邮件模板创建测试以捕获回归:

public class EmailTemplateSnapshotTests : IClassFixture<EmailTestFixture>
{
    private readonly IMjmlTemplateRenderer _renderer;

    public EmailTemplateSnapshotTests(EmailTestFixture fixture)
    {
        _renderer = fixture.Services.GetRequiredService<IMjmlTemplateRenderer>();
    }

    [Fact]
    public async Task WelcomeEmail_NewUser() =>
        await VerifyTemplate("Welcome/NewUser", new Dictionary<string, string>
        {
            { "UserName", "John Doe" },
            { "LoginUrl", "https://example.com/login" }
        });

    [Fact]
    public async Task WelcomeEmail_InvitedUser() =>
        await VerifyTemplate("Welcome/InvitedUser", new Dictionary<string, string>
        {
            { "UserName", "John Doe" },
            { "InviterName", "Jane Admin" },
            { "OrganizationName", "Acme Corp" }
        });

    [Fact]
    public async Task PasswordReset() =>
        await VerifyTemplate("PasswordReset/PasswordReset", new Dictionary<string, string>
        {
            { "UserName", "John Doe" },
            { "ResetLink", "https://example.com/reset/abc123" },
            { "ExpirationMinutes", "30" }
        });

    [Fact]
    public async Task PaymentReceipt() =>
        await VerifyTemplate("Billing/PaymentReceipt", new Dictionary<string, string>
        {
            { "UserName", "John Doe" },
            { "Amount", "$10.00" },
            { "InvoiceNumber", "INV-2025-001" },
            { "Date", "January 15, 2025" }
        });

    private async Task VerifyTemplate(
        string templateName,
        Dictionary<string, string> variables)
    {
        var html = await _renderer.RenderTemplateAsync(templateName, variables);
        await Verify(html, extension: "html")
            .UseMethodName(templateName.Replace("/", "_"));
    }
}

擦除动态值

某些值在测试运行之间会发生变化。擦除它们:

[Fact]
public async Task EmailWithTimestamp_ScrubsDynamicValues()
{
    var html = await _renderer.RenderTemplateAsync("Welcome", variables);

    await Verify(html, extension: "html")
        .ScrubLinesContaining("Generated at:")
        .ScrubInlineGuids();  // 擦除 URL 中的 GUID
}

常见的擦除器

// 擦除日期
.ScrubLinesContaining("Date:")
.AddScrubber(s => Regex.Replace(s, @"\d{4}-\d{2}-\d{2}", "SCRUBBED-DATE"))

// 擦除包含令牌的 URL
.AddScrubber(s => Regex.Replace(s, @"token=[a-zA-Z0-9]+", "token=SCRUBBED"))

// 擦除 GUID
.ScrubInlineGuids()

电子邮件测试的测试夹具

public class EmailTestFixture : IAsyncLifetime
{
    public IServiceProvider Services { get; private set; } = null!;

    public async Task InitializeAsync()
    {
        var services = new ServiceCollection();

        services.AddSingleton<IConfiguration>(new ConfigurationBuilder()
            .AddInMemoryCollection(new Dictionary<string, string?>
            {
                ["SiteUrl"] = "https://example.com"
            })
            .Build());

        services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();

        Services = services.BuildServiceProvider();

        await Task.CompletedTask;
    }

    public Task DisposeAsync() => Task.CompletedTask;
}

Composer 快照测试

测试完整的 Composer 输出,包括主题和元数据:

[Fact]
public async Task SignupInvitation_ComposesCorrectEmail()
{
    var composer = _services.GetRequiredService<IUserEmailComposer>();

    var email = await composer.ComposeSignupInvitationAsync(
        recipientEmail: new EmailAddress("[email protected]"),
        recipientName: new PersonName("John Doe"),
        inviterName: new PersonName("Jane Admin"),
        organizationName: new OrganizationName("Acme Corp"),
        invitationUrl: new AbsoluteUri("https://example.com/invite/abc123"),
        expiresAt: new DateTimeOffset(2025, 12, 31, 0, 0, 0, TimeSpan.Zero));

    // 验证完整的电子邮件对象(主题、收件人、正文)
    await Verify(new
    {
        email.To,
        email.Subject,
        HtmlBody = email.HtmlBody  // 将存储为 .html 扩展名
    });
}

CI 集成

缺少基线时失败

在 CI 中,如果不存在 .verified.html 文件则失败(防止意外接受):

// 在测试设置或 ModuleInitializer 中
VerifierSettings.ThrowOnMissingVerifiedFile();

Git 配置

添加到 .gitattributes 以改进差异处理:

*.verified.html linguist-language=HTML
*.verified.html diff=html

最佳实践

要这样做

// 要这样做:测试每个模板变体
[Fact] Task WelcomeEmail_NewUser_RendersCorrectly()
[Fact] Task WelcomeEmail_InvitedUser_RendersCorrectly()

// 要这样做:使用描述性的测试名称
[Fact] Task PaymentReceipt_WithRefund_ShowsRefundAmount()

// 要这样做:一致地擦除动态值
.ScrubLinesContaining("Generated at:")

// 要这样做:在接受前仔细检查差异
verify review

不要这样做

// 不要这样做:跳过电子邮件测试
// 不要这样做:未经审查自动接受更改
verify accept --all  // 危险!

// 不要这样做:仅测试成功路径
// 不要这样做:忽略快照测试失败

工作流程

  1. 创建模板 - 编写 MJML 模板
  2. 编写测试 - 添加包含示例变量的快照测试
  3. 运行测试 - 首次运行创建 .verified.html
  4. 审查 - 在浏览器中打开,验证渲染效果
  5. 提交 - 将 .verified.html 包含在源代码管理中
  6. 迭代 - 更改导致测试失败,审查差异,如果正确则接受

资源

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.

相关技能