Community程式設計與開發github.com

verify-email-snapshots

使用 Verify 對電子郵件模板進行快照測試,以捕捉回歸問題。驗證渲染的 HTML 輸出是否符合已核准的基準。支援 MJML 模板和任何電子郵件渲染器。

verify-email-snapshots 是什麼?

這個技能(verify-email-snapshots)教導開發者如何使用 Verify 函式庫對電子郵件模板進行快照測試,從而有效捕捉視覺回歸問題。電子郵件模板的輸出是複雜的 HTML,傳統單元測試難以驗證,而快照測試會將渲染後的 HTML 與已核准的基準檔案進行比對,任何非預期的變更都會導致測試失敗,並產生易於檢視的差異。此技能支援任何電子郵件渲染器,並特別針對 MJML 模板提供完整範例,包括基本快照測試、測試各個模板變體、清理動態值(如日期、GUID)、建立測試固定裝置(Test Fixture),以及測試完整的電子郵件合成器輸出(包含主旨和後設資料)。此外,技能還涵蓋了 CI 整合(如遺漏基準檔案時強制失敗)、Git 設定(改善差異顯示)以及最佳實務,例如每個模板變體都應測試、始終檢閱差異後再接受變更。

相容平台~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;
}

合成器快照測試

測試完整的合成器輸出,包括主旨和後設資料:

[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.

相關技能