In this lesson, you will learn how to leverage component rendering tools to assert the behavior and visual state of Blazor components without launching a full browser.
The Challenge of Component State
Unlike standard class libraries, Blazor components (Razor files) are a mix of C# logic and HTML markup. Testing them requires a way to "render" the component into a virtual DOM so you can inspect the generated output. We use libraries like bUnit to provide a test context that simulates the Blazor renderer, allowing you to interact with components as if they were running in the browser.
Asserting UI Behavior
When testing a component, you aren’t just checking if a method returns a value; you are verifying that the component’s internal state translates correctly to the rendered HTML.
For instance, if you have a Counter.razor component, your test must verify that clicking a button triggers a re-render and updates the displayed count.
[Fact]
public void Counter_Increments_WhenButtonClicked()
{
// 1. Arrange: Render the component
using var ctx = new TestContext();
var cut = ctx.RenderComponent<Counter>();
// 2. Act: Find the button and trigger the event
var button = cut.Find("button");
button.Click();
// 3. Assert: Verify the rendered HTML reflects the new state
cut.Find("p").MarkupMatches("<p>Current count: 1</p>");
}
In this example, RenderComponent creates an instance of the component in memory. The Find method allows us to query the rendered DOM nodes using CSS selectors. Finally, MarkupMatches ensures that our expected HTML structure aligns with the component's output.
Avoiding Browser Overhead
The power of this approach lies in its speed. Because these tests run against a virtual DOM in memory, they execute in milliseconds rather than seconds. This allows you to write fine-grained tests for complex component lifecycles, parameter changes, and cascading values without the flakiness often associated with full-browser automation tools like Playwright. By testing the rendered output rather than just the underlying private variables, you ensure that your UI logic is actually visible and accessible to the user.
Key Takeaway: Use component rendering tools to bridge the gap between internal C# logic and external HTML output, ensuring your UI state updates correctly in response to user events.