diff --git a/docs/samples/components/AsyncComponentLoader.razor b/docs/samples/components/AsyncComponentLoader.razor new file mode 100644 index 000000000..ba25e59f0 --- /dev/null +++ b/docs/samples/components/AsyncComponentLoader.razor @@ -0,0 +1,24 @@ +@if (isLoading) +{ +

Loading...

+} +else +{ + @foreach (var item in Items) + { + + } +} + +@code { + [Parameter] public List Items { get; set; } = new(); + + private bool isLoading = true; + + protected override async Task OnInitializedAsync() + { + // Simulate async loading + await Task.Delay(100); + isLoading = false; + } +} diff --git a/docs/samples/components/ListItem.razor b/docs/samples/components/ListItem.razor new file mode 100644 index 000000000..76dfd5d42 --- /dev/null +++ b/docs/samples/components/ListItem.razor @@ -0,0 +1,5 @@ +
@Value
+ +@code { + [Parameter] public string Value { get; set; } = string.Empty; +} diff --git a/docs/samples/tests/xunit/WaitForComponentTest.cs b/docs/samples/tests/xunit/WaitForComponentTest.cs new file mode 100644 index 000000000..addd8b2b2 --- /dev/null +++ b/docs/samples/tests/xunit/WaitForComponentTest.cs @@ -0,0 +1,46 @@ +using Bunit; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Bunit.Docs.Samples; + +public class WaitForComponentTest : BunitContext +{ + [Fact] + public void WaitForComponent_WaitsForSingleComponent() + { + var cut = Render(parameters => parameters + .Add(p => p.Items, ["Item 1"])); + + var listItem = cut.WaitForComponent(); + + Assert.Equal("Item 1", listItem.Find(".list-item").TextContent); + } + + [Fact] + public void WaitForComponents_WaitsForMultipleComponents() + { + var items = new List { "Item 1", "Item 2", "Item 3" }; + var cut = Render(parameters => parameters + .Add(p => p.Items, items)); + + var listItems = cut.WaitForComponents(); + + Assert.Equal(3, listItems.Count); + Assert.Equal("Item 1", listItems.ElementAt(0).Find(".list-item").TextContent); + Assert.Equal("Item 2", listItems.ElementAt(1).Find(".list-item").TextContent); + Assert.Equal("Item 3", listItems.ElementAt(2).Find(".list-item").TextContent); + } + + [Fact] + public void WaitForComponents_WaitsForSpecificCount() + { + var items = new List { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }; + var cut = Render(parameters => parameters + .Add(p => p.Items, items)); + + var listItems = cut.WaitForComponents(5); + + Assert.Equal(5, listItems.Count); + } +} diff --git a/docs/site/docs/interaction/awaiting-async-state.md b/docs/site/docs/interaction/awaiting-async-state.md index 88f6836fb..7b8c326a3 100644 --- a/docs/site/docs/interaction/awaiting-async-state.md +++ b/docs/site/docs/interaction/awaiting-async-state.md @@ -9,7 +9,7 @@ A test can fail if a component performs asynchronous renders. This may be due to You need to handle this specifically in your tests because tests execute in the test framework's synchronization context and the test renderer executes renders in its own synchronization context. If you do not, you will likely experience tests that sometimes pass and sometimes fail. -bUnit comes with two methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForState``1(Bunit.IRenderedComponent{``0},System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method covered on this page, and the [`WaitForAssertion()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForAssertion``1(Bunit.IRenderedComponent{``0},System.Action,System.Nullable{System.TimeSpan})) method covered on the page. +bUnit comes with several methods that help to deal with this issue: the [`WaitForState()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForState``1(Bunit.IRenderedComponent{``0},System.Func{System.Boolean},System.Nullable{System.TimeSpan})) method, the [`WaitForAssertion()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForAssertion``1(Bunit.IRenderedComponent{``0},System.Action,System.Nullable{System.TimeSpan})) method covered on the page, and the component-specific waiting methods [`WaitForComponent()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForComponent``1(Bunit.IRenderedComponent{Microsoft.AspNetCore.Components.IComponent},System.Nullable{System.TimeSpan})) and [`WaitForComponents()`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForComponents``1(Bunit.IRenderedComponent{Microsoft.AspNetCore.Components.IComponent},System.Nullable{System.TimeSpan})) that are covered later on this page. Let's start by taking a look at the `WaitForState` method in more detail. @@ -48,6 +48,42 @@ If the timeout is reached, a The state predicate did not pass before the timeout period passed. -## Debugging code that uses `WaitForState`, `WaitForAssertion`, or `WaitForElement` +## Waiting for components using `WaitForComponent` and `WaitForComponents` + +bUnit provides specialized methods for waiting for child components to appear in the render tree. These methods are useful when testing scenarios where components are rendered asynchronously based on some state change or data loading. + +### Waiting for a single component + +The [`WaitForComponent(TimeSpan?)`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForComponent``1(Bunit.IRenderedComponent{Microsoft.AspNetCore.Components.IComponent},System.Nullable{System.TimeSpan})) method waits until the specified component type is rendered in the DOM and returns the first instance found. + +Consider the following `` component that loads child components asynchronously: + +[!code-cshtml[AsyncComponentLoader.razor](../../../samples/components/AsyncComponentLoader.razor)] + +To test that the `` components are rendered correctly, the `WaitForComponent()` method can be used: + +[!code-csharp[WaitForComponentTest.cs](../../../samples/tests/xunit/WaitForComponentTest.cs?start=12&end=17)] + +### Waiting for multiple components + +The [`WaitForComponents(TimeSpan?)`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForComponents``1(Bunit.IRenderedComponent{Microsoft.AspNetCore.Components.IComponent},System.Nullable{System.TimeSpan})) method waits until at least one instance of the specified component type is rendered in the DOM and returns all instances found: + +[!code-csharp[WaitForComponentTest.cs](../../../samples/tests/xunit/WaitForComponentTest.cs?start=23&end=31)] + +### Waiting for a specific number of components + +The [`WaitForComponents(int, TimeSpan?)`](xref:Bunit.RenderedComponentWaitForHelperExtensions.WaitForComponents``1(Bunit.IRenderedComponent{Microsoft.AspNetCore.Components.IComponent},System.Int32,System.Nullable{System.TimeSpan})) overload waits until at least the specified number of component instances are rendered: + +[!code-csharp[WaitForComponentTest.cs](../../../samples/tests/xunit/WaitForComponentTest.cs?start=38&end=44)] + +> [!NOTE] +> This method waits for **at least** the specified number of components, not exactly that number. If more components are rendered than requested, the method will still succeed and return all found instances. + +> [!NOTE] +> These component wait methods use the same underlying mechanism as `WaitForState()` and will retry their checks every time the component under test renders. + +If the timeout is reached, a exception is thrown with an appropriate error message indicating that the expected component(s) were not found within the timeout period. + +## Debugging code that uses `WaitForState`, `WaitForAssertion`, `WaitForComponent`, `WaitForComponents`, or `WaitForElement` When `bUnit` detects that a debugger is attached (`Debugger.IsAttached`), it will automatically disable the timeout functionality of the "wait for" methods. \ No newline at end of file diff --git a/src/bunit/Extensions/WaitForHelpers/RenderedComponentWaitForhelperExtensions.WaitForComponent.cs b/src/bunit/Extensions/WaitForHelpers/RenderedComponentWaitForhelperExtensions.WaitForComponent.cs new file mode 100644 index 000000000..1f706de84 --- /dev/null +++ b/src/bunit/Extensions/WaitForHelpers/RenderedComponentWaitForhelperExtensions.WaitForComponent.cs @@ -0,0 +1,56 @@ +namespace Bunit; + +/// +/// Provides extension methods for waiting on components within a rendered Blazor component. +/// +public static partial class RenderedComponentWaitForHelperExtensions +{ + /// + /// Waits until the specified component is rendered in the DOM. + /// + /// The rendered component to find the component in. + /// The maximum time to wait for the element to appear. + /// The target component type to wait for. + /// See . + public static IRenderedComponent WaitForComponent( + this IRenderedComponent renderedComponent, + TimeSpan? timeout = null) + where TComponent : IComponent + { + renderedComponent.WaitForState(renderedComponent.HasComponent, timeout); + return renderedComponent.FindComponent(); + } + + /// + /// Waits until the specified number of components are rendered in the DOM and returns their instances. + /// + /// The rendered component in which to search for instances of the specified component. + /// The minimum amount component instances to wait for. + /// The maximum time to wait for the components to appear. Defaults to no specific timeout if not provided. + /// The target component type to wait for. + /// A read-only collection of instances representing the found components. + public static IReadOnlyCollection> WaitForComponents( + this IRenderedComponent renderedComponent, + int matchComponentCount, + TimeSpan? timeout = null) + where TComponent : IComponent + { + renderedComponent.WaitForState( + () => renderedComponent.FindComponents().Count >= matchComponentCount, + timeout); + return renderedComponent.FindComponents(); + } + + /// + /// Waits until the specified component is rendered in the DOM and returns all instances of that component when the first instance is found. + /// + /// The rendered component in which to search for instances of the specified component. + /// The maximum time to wait for the components to appear. Defaults to no specific timeout if not provided. + /// The target component type to wait for. + /// A read-only collection of instances representing the found components. + public static IReadOnlyCollection> WaitForComponents( + this IRenderedComponent renderedComponent, + TimeSpan? timeout = null) + where TComponent : IComponent + => renderedComponent.WaitForComponents(1, timeout); +}