|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the Apache 2.0 License |
| 3 | +// See the LICENSE file in the project root for more information. |
| 4 | +// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone |
| 5 | + |
| 6 | +namespace UnitTest.Components; |
| 7 | + |
| 8 | +public class BootstrapBlazorErrorBoundaryTest : BootstrapBlazorTestBase |
| 9 | +{ |
| 10 | + // 1. Test rendering of child content when there is no exception |
| 11 | + [Fact] |
| 12 | + public void ShouldRenderChildContent_WhenNoException() |
| 13 | + { |
| 14 | + var cut = Context.RenderComponent<BootstrapBlazorErrorBoundary>(parameters => parameters |
| 15 | + .AddChildContent("<p>Normal Content</p>") |
| 16 | + ); |
| 17 | + cut.MarkupMatches("<p>Normal Content</p>"); |
| 18 | + } |
| 19 | + |
| 20 | + // 2. Test rendering custom error content when an exception is thrown and ErrorContent is set |
| 21 | + [Fact] |
| 22 | + public void ShouldRenderCustomErrorContent_WhenExceptionOccurs() |
| 23 | + { |
| 24 | + var errorContentRendered = false; |
| 25 | + |
| 26 | + var cut = Context.RenderComponent<BootstrapBlazorErrorBoundary>(parameters => parameters |
| 27 | + .Add(p => p.ErrorContent, ex => builder => |
| 28 | + { |
| 29 | + errorContentRendered = true; |
| 30 | + builder.OpenElement(0, "div"); |
| 31 | + builder.AddAttribute(1, "class", "custom-error"); |
| 32 | + builder.AddContent(2, $"Custom error caught: {ex.Message}"); |
| 33 | + builder.CloseElement(); |
| 34 | + }) |
| 35 | + .AddChildContent<ExceptionThrowingComponent>() |
| 36 | + ); |
| 37 | + |
| 38 | + cut.MarkupMatches("""<div class="custom-error">Custom error caught: Boom!</div>"""); |
| 39 | + Assert.True(errorContentRendered); |
| 40 | + } |
| 41 | + |
| 42 | + // 3. Test rendering default error content when an exception is thrown and ErrorContent is null |
| 43 | + [Fact] |
| 44 | + public void ShouldRenderDefaultExceptionContent_WhenExceptionOccurs_AndErrorContentIsNull() |
| 45 | + { |
| 46 | + var cut = Context.RenderComponent<BootstrapBlazorErrorBoundary>(parameters => parameters |
| 47 | + .AddChildContent<ExceptionThrowingComponent>() |
| 48 | + ); |
| 49 | + Assert.Contains("Boom!", cut.Markup); |
| 50 | + } |
| 51 | + |
| 52 | + private class ExceptionThrowingComponent : ComponentBase |
| 53 | + { |
| 54 | + protected override void OnInitialized() |
| 55 | + { |
| 56 | + throw new InvalidOperationException("Boom!"); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
0 commit comments