CommunityProgramación y desarrollogithub.com

verificar-instantáneas-correo

Prueba de instantáneas de plantillas de correo electrónico con Verify para detectar regresiones. Valida que el HTML renderizado coincida con la línea base aprobada. Funciona con plantillas MJML y cualquier motor de renderizado de correo.

¿Qué es verificar-instantáneas-correo?

Esta habilidad te permite realizar pruebas de instantáneas (snapshot testing) en plantillas de correo electrónico utilizando la librería Verify, ideal para detectar regresiones visuales en el HTML renderizado. Es especialmente útil cuando trabajas con plantillas MJML, pero funciona con cualquier motor de renderizado de correo. Al capturar el HTML renderizado y compararlo con una línea base aprobada (archivos `.verified.html`), cualquier cambio inesperado hará que la prueba falle, mostrando un diff claro. Esto es crítico porque los correos electrónicos son altamente visuales, difíciles de probar unitariamente y propensos a regresiones. La habilidad incluye ejemplos completos de código C# con xUnit, técnicas para limpiar valores dinámicos (como GUIDs o fechas), integración con CI (lanzar error si falta la línea base) y recomendaciones sobre flujo de trabajo (crear plantilla, escribir test, revisar diff, aceptar). Compatible con las plataformas Verify.Xunit, Verify.NUnit y Verify.MSTest.

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

Installed? Explore more Programación y desarrollo skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Pruebas de Instantáneas de Plantillas de Correo Electrónico con Verify

Cuándo Usar Esta Habilidad

Usa esta habilidad cuando:

  • Estés probando la renderización de plantillas de correo para detectar regresiones
  • Valides que las plantillas MJML se compilen al HTML esperado
  • Revises cambios en correos electrónicos durante la revisión de código (los diffs son visuales)
  • Asegures que la sustitución de variables funcione correctamente

Habilidades relacionadas:

  • aspnetcore/mjml-email-templates - Creación de plantillas MJML
  • aspire/mailpit-integration - Entrega de correos de prueba localmente
  • testing/snapshot-testing - Patrones generales de Verify

¿Por Qué Probar Instantáneas de Correos Electrónicos?

Las plantillas de correo electrónico son:

  1. Visuales - Pequeños cambios pueden romper la renderización en diferentes clientes
  2. Difíciles de probar unitariamente - La salida es HTML complejo, no valores simples
  3. Propensas a regresiones - Los cambios en la plantilla pueden tener efectos no deseados

Las pruebas de instantáneas capturan el HTML renderizado y fallan cuando cambia inesperadamente.


Instalación

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

Prueba Básica de Instantáneas de Correo

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

    var variables = new Dictionary<string, string>
    {
        { "PreviewText", "Has sido invitado a unirte a Acme Corp" },
        { "OrganizationName", "Acme Corporation" },
        { "InviteeName", "Juan Pérez" },
        { "InviterName", "Jane Admin" },
        { "InvitationLink", "https://example.com/invite/abc123" },
        { "ExpirationDate", "31 de diciembre de 2025" }
    };

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

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

Esto crea UserSignupInvitation_RendersCorrectly.verified.html en la primera ejecución.


Revisando Cambios en Correos Electrónicos

Cuando una plantilla cambia, la prueba falla con un diff. Opciones de revisión:

1. Herramienta de Diff Visual

# Configurar herramienta de diff (una vez)
dotnet tool install -g verify.tool
verify accept  # Aceptar todos los cambios pendientes
verify review  # Abrir herramienta de diff

2. Vista Previa en Navegador

Abre el archivo .received.html en un navegador para ver la renderización real.

3. Integración con IDE

La mayoría de los IDEs muestran diffs en línea para archivos .verified.html vs .received.html.


Probar Cada Variante de Plantilla

Crea pruebas para cada plantilla de correo para detectar regresiones:

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", "Juan Pérez" },
            { "LoginUrl", "https://example.com/login" }
        });

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

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

    [Fact]
    public async Task PaymentReceipt() =>
        await VerifyTemplate("Billing/PaymentReceipt", new Dictionary<string, string>
        {
            { "UserName", "Juan Pérez" },
            { "Amount", "$10.00" },
            { "InvoiceNumber", "INV-2025-001" },
            { "Date", "15 de enero 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("/", "_"));
    }
}

Limpiando Valores Dinámicos

Algunos valores cambian entre ejecuciones de prueba. Límpialos:

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

    await Verify(html, extension: "html")
        .ScrubLinesContaining("Generado en:")
        .ScrubInlineGuids();  // Limpia GUIDs en URLs
}

Limpiadores Comunes

// Limpiar fechas
.ScrubLinesContaining("Fecha:")
.AddScrubber(s => Regex.Replace(s, @"\d{4}-\d{2}-\d{2}", "FECHA-LIMPIADA"))

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

// Limpiar GUIDs
.ScrubInlineGuids()

Fixture de Prueba para Pruebas de Correo

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;
}

Pruebas de Instantáneas del Compositor

Prueba la salida completa del compositor, incluyendo asunto y metadatos:

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

    var email = await composer.ComposeSignupInvitationAsync(
        recipientEmail: new EmailAddress("[email protected]"),
        recipientName: new PersonName("Juan Pérez"),
        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));

    // Verificar el objeto completo del correo (asunto, para, cuerpo)
    await Verify(new
    {
        email.To,
        email.Subject,
        HtmlBody = email.HtmlBody  // Se almacenará con extensión .html
    });
}

Integración con CI

Fallar si Falta Línea Base

En CI, falla si no existe el archivo .verified.html (previene la aceptación accidental):

// En la configuración de prueba o ModuleInitializer
VerifierSettings.ThrowOnMissingVerifiedFile();

Configuración de Git

Agrega a .gitattributes para mejorar el manejo de diffs:

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

Mejores Prácticas

HACER

// HACER: Probar cada variante de plantilla
[Fact] Task WelcomeEmail_NewUser_RendersCorrectly()
[Fact] Task WelcomeEmail_InvitedUser_RendersCorrectly()

// HACER: Usar nombres de prueba descriptivos
[Fact] Task PaymentReceipt_WithRefund_ShowsRefundAmount()

// HACER: Limpiar valores dinámicos de forma consistente
.ScrubLinesContaining("Generado en:")

// HACER: Revisar los diffs cuidadosamente antes de aceptar
verify review

NO HACER

// NO HACER: Saltarse las pruebas de correo
// NO HACER: Auto-aceptar cambios sin revisión
verify accept --all  // ¡Peligroso!

// NO HACER: Probar solo el camino feliz
// NO HACER: Ignorar fallos en pruebas de instantáneas

Flujo de Trabajo

  1. Crear plantilla - Escribe la plantilla MJML
  2. Escribir prueba - Agrega una prueba de instantánea con variables de ejemplo
  3. Ejecutar prueba - La primera ejecución crea .verified.html
  4. Revisar - Abre en el navegador, verifica la renderización
  5. Confirmar - Incluye .verified.html en el control de versiones
  6. Iterar - Los cambios fallan la prueba, revisa el diff, acepta si es correcto

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.

Skills relacionados