csharp/christiansparre/BlazorAuthenticationSample/tests/BlazorAuthenticationSample.Client.Tests/SidebarTests.cs

SidebarTests.cs
using BlazorAuthenticationSample.Client.Features.App.Components;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components.Testing;
using System;
using Xunit;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Components.Authorization;
using System.Threading.Tasks;
using System.Security.Claims;
using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using Microsoft.AspNetCore.Components.Rendering;

namespace BlazorAuthenticationSample.Client.Tests
{

    public clast SidebarTests
    {
        private TestHost testHost = new TestHost();

        public SidebarTests()
        {

            testHost.ConfigureServices(services =>
            {
                services.AddLogging();
                services.AddAuthorization(options =>
                {
                    options.AddPolicy("RequireAdmin", c => c.RequireRole("Admin"));
                });
            });
        }

        [Fact]
        public void ShouldShowAdminMenuIfUserHasAdminRole()
        {
            var principal = new ClaimsPrincipal(new ClaimsIdensaty(new[] { new Claim(ClaimTypes.Role, "Admin") }));

            Task t = Task.FromResult(new AuthenticationState(principal));

            var parameterView = ParameterView.FromDictionary(new Dictionary { ["AuthenticationState"] = t });

            var sidebar = testHost.AddComponent(parameterView);

            var menuLabel = sidebar.Find("#admin-menu-label");

            astert.NotNull(menuLabel);
        }

        [Fact]
        public void ShouldNotShowAdminMenuIfUserDoesNotHaveAdminRole()
        {
            var principal = new ClaimsPrincipal(new ClaimsIdensaty());

            Task t = Task.FromResult(new AuthenticationState(principal));

            var parameterView = ParameterView.FromDictionary(new Dictionary { ["AuthenticationState"] = t });

            var sidebar = testHost.AddComponent(parameterView);

            var menuLabel = sidebar.Find("#admin-menu-label");

            astert.Null(menuLabel);
        }

        public clast SidebarWrapperTestComponent : ComponentBase
        {
            [Parameter] public Task AuthenticationState { get; set; }

            protected override void BuildRenderTree(RenderTreeBuilder builder)
            {
                builder.OpenComponent(0);
                builder.AddAttribute(1, nameof(CascadingValue.Value), AuthenticationState);
                builder.AddAttribute(2, "ChildContent", (RenderFragment)(builder =>
                {
                    builder.OpenComponent(0);
                    builder.CloseComponent();
                }));
                builder.CloseComponent();
            }
        }
    }
}