verify-email-snapshots

Teste de snapshot de templates de e-mail usando Verify para detectar regressões. Valida se a saída HTML renderizada corresponde à linha de base aprovada. Funciona com templates MJML e qualquer renderizador de e-mail.

O que é verify-email-snapshots?

Este skill permite testar templates de e-mail através de snapshot testing utilizando a biblioteca Verify, garantindo que alterações no código não quebrem a renderização esperada. Ele é especialmente útil para validar templates MJML, mas funciona com qualquer renderizador de e-mail que produza HTML. A principal vantagem é capturar regressões visuais em templates que seriam difíceis de testar com testes unitários tradicionais, já que a saída é HTML complexo. No fluxo de trabalho, o desenvolvedor escreve testes que renderizam o template com variáveis de exemplo e comparam o HTML gerado com um arquivo de linha de base aprovado (.verified.html). Quando o template muda, o teste falha e exibe um diff, permitindo revisão visual ou via ferramentas de diff. O skill também oferece funcionalidades para limpar valores dinâmicos (como datas, GUIDs e tokens) antes da comparação, e suporte para testes de composição completa de e-mail (assunto, destinatário e corpo). A integração com CI é facilitada com configurações que impedem a aceitação acidental de novas linhas de base e melhoram o diff no Git. Plataformas suportadas: .NET com xUnit, NUnit ou MSTest.

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

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Teste de Snapshot de Templates de E-mail com Verify

Quando Usar Este Skill

Use este skill quando:

  • Testar a renderização de templates de e-mail para regressões
  • Validar que templates MJML compilam para o HTML esperado
  • Revisar alterações em e-mails durante code review (diffs são visuais)
  • Garantir que a substituição de variáveis funcione corretamente

Skills relacionados:

  • aspnetcore/mjml-email-templates - Criação de templates MJML
  • aspire/mailpit-integration - Testar envio de e-mail localmente
  • testing/snapshot-testing - Padrões gerais do Verify

Por que Testar E-mails com Snapshot?

Templates de e-mail são:

  1. Visuais - Pequenas alterações podem quebrar a renderização em diferentes clientes
  2. Difíceis de testar unitariamente - A saída é HTML complexo, não valores simples
  3. Propensos a regressões - Alterações no template podem ter efeitos não intencionais

O teste de snapshot captura o HTML renderizado e falha quando ele muda inesperadamente.


Instalação

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

Teste Básico de Snapshot de E-mail

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

    var variables = new Dictionary<string, string>
    {
        { "PreviewText", "Você foi convidado para participar da Acme Corp" },
        { "OrganizationName", "Acme Corporation" },
        { "InviteeName", "João Silva" },
        { "InviterName", "Ana Admin" },
        { "InvitationLink", "https://exemplo.com/invite/abc123" },
        { "ExpirationDate", "31 de dezembro de 2025" }
    };

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

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

Isso cria UserSignupInvitation_RendersCorrectly.verified.html na primeira execução.


Revisando Alterações em E-mails

Quando um template muda, o teste falha com um diff. Opções de revisão:

1. Ferramenta de Diff Visual

# Configurar ferramenta de diff (uma vez)
dotnet tool install -g verify.tool
verify accept  # Aceitar todas as alterações pendentes
verify review  # Abrir ferramenta de diff

2. Visualização no Navegador

Abra o arquivo .received.html em um navegador para ver a renderização real.

3. Integração com IDE

A maioria das IDEs mostra diffs inline para arquivos .verified.html vs .received.html.


Testar Cada Variante do Template

Crie testes para cada template de e-mail para capturar regressões:

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", "João Silva" },
            { "LoginUrl", "https://exemplo.com/login" }
        });

    [Fact]
    public async Task WelcomeEmail_InvitedUser() =>
        await VerifyTemplate("Welcome/InvitedUser", new Dictionary<string, string>
        {
            { "UserName", "João Silva" },
            { "InviterName", "Ana Admin" },
            { "OrganizationName", "Acme Corp" }
        });

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

    [Fact]
    public async Task PaymentReceipt() =>
        await VerifyTemplate("Billing/PaymentReceipt", new Dictionary<string, string>
        {
            { "UserName", "João Silva" },
            { "Amount", "R$ 10,00" },
            { "InvoiceNumber", "FAT-2025-001" },
            { "Date", "15 de janeiro de 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("/", "_"));
    }
}

Limpeza de Valores Dinâmicos

Alguns valores mudam entre execuções de teste. Limpe-os:

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

    await Verify(html, extension: "html")
        .ScrubLinesContaining("Generated at:")
        .ScrubInlineGuids();  // Limpa GUIDs em URLs
}

Limpadores Comuns

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

// Limpar URLs com tokens
.AddScrubber(s => Regex.Replace(s, @"token=[a-zA-Z0-9]+", "token=SCRUBBED"))

// Limpar GUIDs
.ScrubInlineGuids()

Fixture de Teste para Testes de E-mail

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://exemplo.com"
            })
            .Build());

        services.AddSingleton<IMjmlTemplateRenderer, MjmlTemplateRenderer>();

        Services = services.BuildServiceProvider();

        await Task.CompletedTask;
    }

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

Testes de Snapshot do Composer

Teste a saída completa do composer, incluindo assunto e metadados:

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

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

    // Verificar o objeto de e-mail completo (assunto, para, corpo)
    await Verify(new
    {
        email.To,
        email.Subject,
        HtmlBody = email.HtmlBody  // Será armazenado com extensão .html
    });
}

Integração com CI

Falhar se Linha de Base Ausente

No CI, falhe se nenhum arquivo .verified.html existir (evita aceitação acidental):

// Na configuração do teste ou ModuleInitializer
VerifierSettings.ThrowOnMissingVerifiedFile();

Configuração do Git

Adicione ao .gitattributes para melhorar o tratamento de diffs:

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

Melhores Práticas

FAÇA

// FAÇA: Teste cada variante do template
[Fact] Task WelcomeEmail_NewUser_RendersCorrectly()
[Fact] Task WelcomeEmail_InvitedUser_RendersCorrectly()

// FAÇA: Use nomes de teste descritivos
[Fact] Task PaymentReceipt_WithRefund_ShowsRefundAmount()

// FAÇA: Limpe valores dinâmicos de forma consistente
.ScrubLinesContaining("Generated at:")

// FAÇA: Revise diffs cuidadosamente antes de aceitar
verify review

NÃO FAÇA

// NÃO FAÇA: Pule testes de e-mail
// NÃO FAÇA: Aceite alterações automaticamente sem revisão
verify accept --all  // Perigoso!

// NÃO FAÇA: Teste apenas o caminho feliz
// NÃO FAÇA: Ignore falhas em testes de snapshot

Fluxo de Trabalho

  1. Criar template - Escreva o template MJML
  2. Escrever teste - Adicione teste de snapshot com variáveis de exemplo
  3. Executar teste - A primeira execução cria .verified.html
  4. Revisar - Abra no navegador, verifique a renderização
  5. Commitar - Inclua .verified.html no controle de versão
  6. Iterar - Alterações falham no teste, revise o diff, aceite se correto

Recursos

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.

Habilidades Relacionadas